为什么借用顺序在 Rust 中很重要? [英] Why does the order of borrowing matter in rust?
问题描述
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
在这两种情况下都可变地借用了 name,而 push_str 也可变地借用了 name,那么为什么第一个示例编译?
all I did was switch the order of the two functions but it seems like x
has mutably borrowed name and push_str has also mutably borrowed name in both situations, so why does the first example compile?
如果我去掉对 say_hello()
的调用,为什么即使仍然有两个可变借用,两者的顺序无关紧要?
If I take out the call to say_hello()
why does the order of the two not matter even though there are still two mutable borrows?
这是相似的吗?
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 的借用规则之一是 可变引用是独占的.意思是,当 x
活着时,不能使用 name
.
One of Rust's borrowing rules is that mutable references are exclusive. Meaning, while x
is alive, name
cannot be used.
那么,为什么即使 x
仍在作用域内,第一个示例仍能编译?因为 Rust 也有 non-词法生命周期 意味着 x
停止生活";上次使用后.
So, why does the first example compile even if x
is still in scope? Because Rust also has non-lexical lifetimes meaning x
stops "living" after its last use.
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 中很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!