[英]Why does the order of borrowing matter in rust?
fn say_hello(s: &str) {
println!("Hello {}", s);
}
Why does this work为什么这行得通
fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
say_hello(x);
name.push_str(" Brown");
}
but this doesn't?但这不是吗?
fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
name.push_str(" Brown");
say_hello(x);
}
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?我所做的只是切换这两个函数的顺序,但似乎
x
在这两种情况下都可变地借用了名称,而 push_str 也可变地借用了名称,那么为什么第一个示例会编译?
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?如果我拨打
say_hello()
的电话,为什么即使还有两个可变借用,两者的顺序也不重要?
Edit: Is this similar?编辑:这是相似的吗?
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");
}
One of Rust's borrowing rules is that mutable references are exclusive . Rust 的借用规则之一是可变引用是独占的。 Meaning, while
x
is alive, name
cannot be used.意思是,当
x
还活着时,不能使用name
。
So, why does the first example compile even if x
is still in scope?那么,为什么即使
x
仍在 scope 中,第一个示例也会编译? Because Rust also has non-lexical lifetimes meaning x
stops "living" after its last use.因为 Rust 也有非词法生命周期,这意味着
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
}
Because in your first case, the two mutable borrow scopes don't overlap and you have only one borrow at any given point of time;因为在您的第一种情况下,两个可变借用范围不重叠,并且您在任何给定时间点只有一个借用; but in your second case, they overlap, which means you have multiple mutable borrows at the certain point of time, which is not allowed:
但在第二种情况下,它们重叠,这意味着您在某个时间点有多个可变借用,这是不允许的:
First case:第一种情况:
fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
say_hello(x); // the mutable borrow ends here
name.push_str(" Brown"); // a new mutable borrow
}
Second case:第二种情况:
fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
name.push_str(" Brown"); // the first mutable borrow is still
// alive, you have two mutable borrows here
say_hello(x); // the first mutable borrow ends here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.