【发布时间】:2016-06-17 13:11:40
【问题描述】:
在 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 borrow-checker