rust - 在建模收容关系时了解生命周期管理

我试着用一生的时间把我的头缠在生锈的东西上。当我在执行一个关系建模练习时,我遇到了以下错误。

error: cannot borrow `bob` as mutable because `bob.gender` is also borrowed as immutable [E0502]

代码在这里:
// Business Case:
// Design a person type.  A person may own a Car.  A person should be able to buy and sell cars.
// Two persons should be able to exchange (or trade) their cars.
//
// Purpose of exercise:
// Understand lifetime management in Rust while modeling containment relationship.
// (meaning: when an object contains a reference to another object.)

struct Car {
    make: &'static str,
    model: &'static str,
    year: &'static str,
}

struct Person<'a> {
    name: &'static str,
    gender: &'static str,
    car: Option<&'a Car>,
}

impl<'a> Person<'a> {
    fn new(name: &'static str, gender: &'static str, car: Option<&'a Car>) -> Person<'a> {
        Person {
            name: name,
            gender: gender,
            car: None,
        }
    }

    fn buy_car(&mut self, c: &'a Car) {
        self.car = Some(c);
    }

    fn sell_car(&mut self) {
        self.car = None;
    }
}

fn main() {
    let pickup = Car {
        make: "Ford",
        model: "F250",
        year: "2006",
    };

    let mut bob = Person::new("Bob", "Male", None);

    println!("A {:?} whose name is {:?} has just purchased a 2006 {:?}.",
             bob.gender,
             bob.name,
             bob.buy_car(&pickup));
}

有谁能告诉我我到底缺了什么吗?我不确定引用计数或框是否是正确的方法,需要更多的了解。

最佳答案

您的问题归结为使用buy_car(不返回任何内容)而您可能打算使用bob.car。去做那个。。您还需要为fmt::Debug结构实现Car。这是给你的一个解决方案。。请注意我添加的所有// <----- partshere it is on the Playground):

#[derive(Debug)] // <------------ Have the compiler implement fmt::Debug for you
struct Car {
    make: &'static str,
    model: &'static str,
    year: &'static str,
}

struct Person<'a> {
    name: &'static str,
    gender: &'static str,
    car: Option<&'a Car>,
}

impl<'a> Person<'a> {
    fn new(name: &'static str, gender: &'static str, car: Option<&'a Car>) -> Person<'a> {
        Person {
            name: name,
            gender: gender,
            car: None,
        }
    }

    fn buy_car(&mut self, c: &'a Car) {
        self.car = Some(c);
    }

    fn sell_car(&mut self) {
        self.car = None;
    }
}

fn main() {
    let pickup = Car {
        make: "Ford",
        model: "F250",
        year: "2006",
    };

    let mut bob = Person::new("Bob", "Male", None);

    bob.buy_car(&pickup);   // <------- Buy the car separately

    println!("A {:?} whose name is {:?} has just purchased a 2006 {:?}.",
             bob.gender,
             bob.name,
             bob.car); // <------------ Pass the car into the debug string
}

作为旁白,我会在适当的地方使用String来减少传递引用和生命周期的需要。也许在你的小例子中并不那么重要,但是随着代码变得越来越大,它们会变得很棘手。

本文翻译自 https://stackoverflow.com/questions/39113799/

网站遵循 CC BY-SA 4.0 协议,转载或引用请注明出处。

标签 rust lifetime containment


相关文章:

rust - 如何阅读基于Tokio的Hyper请求的整个正文?

rust - 如何使用可变成员Vec?

rust - 如何为具有生命周期的结构实现“具有静态生命周期的特征”?

rust - 如何通过libc :: getgroups为用户获取组?

rust - 允许使用Rust稳定的夜间通道并行编译代码有多困难?

ios - 容器视图控制器中的tableviewcontroller:以编程方式选择uitableviewcell,突出显示闪烁

jquery - jQuery可拖动无法与遏制一起使用

c++ - 避免循环依赖-需要相互遏制

reference - 如何将借入的值包装在也是借入的值的新类型中?

pointers - 过滤Vec <String>时无法移出借用的内容