I wrote this code that borrows a mutable variable more than once and compiles without any error, but according to The Rust Programming Language this should not compile:
fn main() {
let mut s = String::from("hello");
println!("{}", s);
test_three(&mut s);
println!("{}", s);
test_three(&mut s);
println!("{}", s);
}
fn test_three(st: &mut String) {
st.push('f');
}
(playground)
Is this a bug or there is new feature in Rust?
Nothing weird happens here; the mutable borrow becomes void every time the test_three
function concludes its work (which is right after it's called):
fn main() {
let mut s = String::from("hello");
println!("{}", s); // immutably borrow s and release it
test_three(&mut s); // mutably borrow s and release it
println!("{}", s); // immutably borrow s and release it
test_three(&mut s); // mutably borrow s and release it
println!("{}", s); // immutably borrow s and release it
}
The function doesn't hold its argument - it only mutates the String
it points to and releases the borrow right afterwards, because it is not needed anymore:
fn test_three(st: &mut String) { // st is a mutably borrowed String
st.push('f'); // the String is mutated
} // the borrow claimed by st is released
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With