我编写了这段代码,该代码多次借用了一个可变变量,并且编译时没有任何错误,但是根据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)

这是Bug还是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

09-25 18:38