rust - 如何告诉 Rust 编译器借用已经结束?

标签 rust borrow-checker

同时 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/

相关文章:

data-structures - 为什么由于 "overflow while adding drop-check rules"无法实例化数据结构?

asynchronous - rust future ::选择循环中修改局部变量

rust - 构建向量树

rust - 用写!带有字符串而不是字符串文字的宏

rust - 将 u16(或 u32、u64)的数组(或向量)转换为 u8 的数组

syntax - 特征中的静态函数可以调用同一特征中的另一个静态函数吗?

rust - 阐明在函数签名中将两个对不同范围的引用对象的引用绑定(bind)到相同生命周期的含义

rust - 为什么转移所有权后可以使用非捕获闭包?

generics - 为什么移动闭包不会捕获具有通用类型的值?

rust - 从功能参数实现具有生命周期限制的切片的特征