I have 2 example code.
1st Example Code
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = & s;
println!("{}", r2);
}
2nd Example Code
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = & s;
println!("{}", r1);
}
What I confuse is why 1stExampleCode work fine, but 2ndExampleCode create compile error as below
cannot borrow 's' as immutable because it is also borrowed as mutable
As I know, in both Example code I borrow r1 did a mutable borrow of s while r2 did a immutable borrow of s. So why 1stExampleCode is not error since s is borrowed as both mutable and immutable at the same time. Or because r1 is not used so it's not create any error.