Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are multiple mutable borrows possible in the same scope?

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?

like image 453
mojtab23 Avatar asked Sep 20 '17 11:09

mojtab23


Video Answer


1 Answers

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
like image 160
ljedrz Avatar answered Oct 24 '22 02:10

ljedrz