moj*_*b23 3 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');
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
这是一个错误还是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
}
Run Code Online (Sandbox Code Playgroud)
该函数不保持其参数 - 它只会改变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
Run Code Online (Sandbox Code Playgroud)