1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
fn main() {
/* heap data deep copy */
let s1 = String::from("Hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
/* stack data copy */
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
/* functions */
let s = String::from("hello");
takes_owership(s);
let x = 5;
makes_copy(x);
/* return values and scope */
let s1 = gives_owership();
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2);
/* parameters */
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
/* reference(borrowing) */
let s1 = String::from("hello");
let len = calculate_length_ref(&s1);
println!("The length of '{}' is {}.", s1, len);
/* mutable reference */
let mut s = String::from("hello");
change(&mut s);
/* mutable and immutable */
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s;
println!("{}", r3);
/* slice */
let mut s = String::from("hello world");
let word = first_word_index(&s);
s.clear();
println!("the first word index: 0-{}", word);
/* string slice */
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world);
/* slice first word */
let mut s = String::from("hello world");
let word = first_word(&s);
println!("the first word: {}", word);
s.clear();
}
fn takes_owership(some_string: String) {
println!("{}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
}
fn gives_owership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn calculate_length_ref(s: &String) -> usize {
s.len()
}
fn change(some_string: &mut String) {
some_string.push_str(", world!");
}
fn first_word_index(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
|