File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -57,3 +57,4 @@ in a controlled repository now.
57
57
* ` closure-example.rs ` : example of Rust closure
58
58
* ` iterator-example.rs ` : example of Rust iterator
59
59
* ` lifetimes-example.rs ` : example involving Rust lifetimes
60
+ * ` strref.rs ` : example involving Rust string clones and copies
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments