Skip to content

Commit 0439f8f

Browse files
committed
added strref example
1 parent 5cf4cf1 commit 0439f8f

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,4 @@ in a controlled repository now.
5757
* `closure-example.rs`: example of Rust closure
5858
* `iterator-example.rs`: example of Rust iterator
5959
* `lifetimes-example.rs`: example involving Rust lifetimes
60+
* `strref.rs`: example involving Rust string clones and copies

strref.rs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
fn main() {
2+
let s = "hello".to_string();
3+
let rs = &s;
4+
let rrs: &&String = &rs;
5+
// Prints hello.
6+
println!("{}", *rrs);
7+
8+
let s = "hello".to_string();
9+
// This takes s by reference.
10+
// Clippy will warn you that you don't need to clone here.
11+
let cs: String = s.clone();
12+
// Prints hello.
13+
println!("{}", cs);
14+
15+
let s = "hello".to_string();
16+
let rs = &s;
17+
// This takes rs by reference, but then dereferences it automatically.
18+
let cs: String = rs.clone();
19+
// Prints hello.
20+
println!("{}", cs);
21+
22+
let s: &str = "hello";
23+
// This would clone the &str reference, so it fails to compile.
24+
// let cs: String = s.clone();
25+
let cs: String = s.to_owned();
26+
// Also acceptable above would have been:
27+
// let cs: String = s.to_string();
28+
// let cs: String = String::from(s);
29+
// let cs: String = s.into();
30+
// Those last two will eat a copy of s, since &str is copy, since
31+
// references are copy. So you could still do this:
32+
// println!("{}", s);
33+
// Prints hello.
34+
println!("{}", cs);
35+
}

0 commit comments

Comments
 (0)