Skip to content

Commit 9ed2f9a

Browse files
committed
feat: mutable and immutable refs
1 parent 6db6932 commit 9ed2f9a

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

notes.txt

+32-1
Original file line numberDiff line numberDiff line change
@@ -272,4 +272,35 @@
272272
let mut s = String::from("Brendan");
273273

274274
let r1 = &s;
275-
let r2 = &mut s;
275+
let r2 = &mut s;
276+
277+
the immutable references are need to be used before initialization of mutable refence.
278+
Otherwise it causes error:
279+
280+
this code failse:
281+
282+
let mut s = String::from("hello");
283+
284+
let r1 = &s;
285+
let r2 = &s;
286+
287+
println!("{} and {}", r1, r2);
288+
289+
let r3 = &mut s;
290+
291+
println!("{}", r2); // here r2, immutable ref is being used after muatble
292+
293+
println!("{}", r3);
294+
295+
this code works:
296+
297+
let mut s = String::from("hello");
298+
299+
let r1 = &s;
300+
let r2 = &s;
301+
302+
println!("{} and {}", r1, r2);
303+
304+
let r3 = &mut s;
305+
306+
println!("{}", r3);

projects/ownership/src/main.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
fn main() {
2-
let mut s = String::from("Brendan");
3-
2+
let mut s = String::from("hello");
43
let r1 = &s;
5-
let r2 = &mut s;
6-
7-
println!("{}, {}", r1, r2);
4+
let r2 = &s;
5+
6+
println!("{} and {}", r1, r2);
7+
8+
let r3 = &mut s;
9+
println!("{}", r3);
810
}

0 commit comments

Comments
 (0)