同时 checking out tutorials关于 Rust,我遇到了借用检查器的问题。以下代码无法编译:
struct Car {
model: String,
}
struct Person<'a> {
car: Option<&'a Car>,
}
impl<'a> Person<'a> {
fn new() -> Person<'a> {
Person { car: None }
}
fn buy_car(&mut self, c: &'a Car) {
// how to say that Person don't borrow the old car any longer?
self.car = Some(c);
}
}
fn main() {
let civic = Car { model: "Honda Civic".to_string() };
let mut ghibli = Car { model: "Maserati Ghibli".to_string() };
let mut bob = Person::new();
bob.buy_car(&ghibli);
bob.buy_car(&civic);
// error: cannot borrow `ghibli` as mutable because it is also borrowed as immutable
let anything = &mut ghibli;
}
我明白,由于它的词法性质,Rust 的借用检查器无法识别 ghibli
的借用。已经结束了。
但我真的很想知道如何用 Rust 方式解决这个问题?我必须使用 Rc<T>
吗?或 Box<T>
以某种方式?
最佳答案
告诉借用检查器借用结束的“Rust 方式”是引入一个新的作用域:
fn main() {
let civic = Car{model: "Honda Civic".to_string()};
let mut ghibli = Car{model: "Maserati Ghibli".to_string()};
{
let mut bob = Person::new();
bob.buy_car(&ghibli);
bob.buy_car(&civic);
}
let anything = &mut ghibli;
}
但是您必须意识到,在您的示例中(并且可能在大多数情况下)借用检查器是正确的。
Bob
借用了对 ghibli
的引用。它仍然出现在 car
字段中 main 方法的末尾。
关于rust - 如何告诉 Rust 编译器借用已经结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882477/