为什么在同一范围内可以进行多个可变借用? [英] Why are multiple mutable borrows possible in the same scope?
问题描述
我写了这段代码,它多次借用一个可变变量并且编译没有任何错误,但是根据 Rust 编程语言这不应该编译:
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');
}
(游乐场)
这是一个错误还是 Rust 中有新功能?
Is this a bug or there is new feature in Rust?
推荐答案
这里没有发生任何奇怪的事情;每次 test_three
函数结束其工作(即在它被调用之后)时,可变借用变为无效:
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
}
该函数不保存它的参数 - 它只改变它指向的 String
并在之后立即释放借用,因为不再需要它:
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
这篇关于为什么在同一范围内可以进行多个可变借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!