Reputation: 3176
I am learning rust, I am trying to understand references.
As per the rust's book -> https://doc.rust-lang.org/nightly/book/ch04-02-references-and-borrowing.html
It says
Note that a reference’s scope starts from where it is introduced
and continues through the last time that reference is used.
And goes on showing (from the book):
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);
// variables r1 and r2 will not be used after this point !! ... okay..?
BUT when I try to reproduce this, I get no error
My example (no error)
fn valid() {
let s = String::from("hi");
let r1 = &s; // valid immutable reference
let r2 = &s; // valid immutable reference
println!("{}, {}", r1, r2);
println!("{}", r1); // Why am I able to use r1 again here??
}
Upvotes: 0
Views: 111
Reputation: 21926
I think you misunderstood what you read. I'm assuming you're referencing this bit of code in the linked resource:
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);
// variables r1 and r2 will not be used after this point
let r3 = &mut s; // no problem
println!("{}", r3);
The point of the code is that since there is no further use of the shared references r1
and r2
it's okay to take the mutable reference r3
. If you try to use one of them after doing so you'll get an error:
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s; // ERROR, no longer after last use of r1
println!("{}", r1);
The point of the example isn't that you can't use r1
and r2
after that line, it's that you cannot take a mutable reference &mut
while something is still holding on to a shared reference &
.
Upvotes: 2
Reputation: 2507
Because you have now changed when the "last use" of r1 is to be at the second print.
You decide when the reference should end and you do so by not using it after a given point. If you add a later use, then you have clearly decided on a new "last use" and so the compiler obliges.
Upvotes: 4