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

时间:2017-09-20 11:05:21

标签: rust borrow-checker

我编写了这个代码,它不止一次地借用了一个可变变量并且编译时没有任何错误,但根据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中有新功能?

1 个答案:

答案 0 :(得分:6)

这里没有什么奇怪的事情发生;每当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