Why are multiple mutable borrows possible in the same scope?

落爺英雄遲暮 提交于 2020-12-09 04:42:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/46320374/why-are-multiple-mutable-borrows-possible-in-the-same-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!