fn say_hello(s: &str) {
println!("Hello {}", s);
}
为什么这行得通fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
say_hello(x);
name.push_str(" Brown");
}
但这不是吗?fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
name.push_str(" Brown");
say_hello(x);
}
我所做的只是切换两个函数的顺序,但看起来像 x
在这两种情况下都可变地借用了名称,而 push_str 也可变地借用了名称,那么为什么第一个示例编译?如果我调用
say_hello()
即使仍然有两个可变借用,为什么两者的顺序无关紧要?编辑:
这是相似的吗?
fn change_string(s: &mut String) { // s is mutably borrowed but isn't used yet
println!("{}", s.is_empty()); // so the scopes don't overlap even though is_empty is making an immutable borrow?
s.push_str(" Brown");
}
最佳答案
Rust 的借用规则之一是 mutable references are exclusive .意思是,而 x
还活着,name
不能使用。
那么,为什么第一个示例即使 x
也能编译?还在范围内吗?因为 Rust 也有 non-lexical lifetimes含义 x
在最后一次使用后停止“生活”。
fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
say_hello(x); // "x"s lifetime ends here, releasing the exclusive borrow
name.push_str(" Brown"); // "name" can be used again
}
关于rust - 为什么借用顺序在 rust 中很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959393/