在建模包含关系时了解生命周期管理

时间:2016-08-24 03:11:45

标签: rust lifetime containment

我正试图将我的脑袋包裹在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));
}

任何人都可以了解我在这里错过了什么?我不确定引用计数或Box是否可行,需要更深入的了解。

1 个答案:

答案 0 :(得分:1)

您的问题归结为使用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来减少传递引用和生命周期的需要。在你的小例子中可能不是那么重要,但随着代码变大,它们会变得棘手。