mojtab23
mojtab23

Reputation: 2675

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?

Upvotes: 5

Views: 778

Answers (1)

ljedrz
ljedrz

Reputation: 22193

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

Upvotes: 9

Related Questions