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");
}
s
)可以重新借用为不可变引用(is_empty()
的self
),但是在不可变引用存在时无法使用可变引用,但由于它仅在s.is_empty()
表达式期间存在,因此在此之后使用s
并不是问题。 - kmdreko