References and Borrowing
References
It is always difficult to pass the ownership completely from one scope to another scope. So we have concept of referencing as well which makes a little bit easier for passing the data by reference.
let mut s1 = String::from("hello world");
let s2 = &s1;
Here in the code s2 is borrowing s1 using reference. This is immutable borrowing. That means s2 just wants to read the memory block and that's it.
let mut s1 = String::from("hello world");
let s2 = &s1;
let s3 = &mut s1;
In the above code s3 is borrowing s1 mutably and this means s3 could change value of s1's data
There could be any number of immutable borrows but only ONE mutable borrow to avoid any race conditions.
let mut s1 = String::from("hello world");
let s3 = &mut s1;
let s4 = &mut s1;
println!("{}", s3);
println!("{}", s1);
The above code is ERROR because s4 is also borrowed as mutable. We could have eliminated the error if had not used println!
at line 6 using s3.
Last updated
Was this helpful?