为什么在同一个范围内可以进行多次可变借用?

Why are multiple mutable borrows possible in the same scope?

我写的这段代码多次借用了一个可变变量并且编译没有任何错误,但是根据 The Rust Programming Language 这不应该编译:

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)

这是一个错误还是 Rust 中有新功能?

这里没有发生任何奇怪的事情;每次 test_three 函数结束其工作时(就在它被调用之后),可变借用变为无效:

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
}

该函数不保存它的参数 - 它只改变它指向的 String 并随后立即释放借用,因为不再需要它了:

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