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

2023-12-03

我编写了这段代码,多次借用可变变量并且编译时没有任何错误,但是根据Rust 编程语言这不应该编译:

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');
}

(操场)

这是一个错误还是 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么同一范围内可以进行多个可变借用? 的相关文章

随机推荐