0

我正试图围绕 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 是否可行,需要更多了解。

4

1 回答 1

1

您的问题归结为您使用buy_car(不返回任何内容)您可能打算使用bob.car. 为此..您还需要fmt::Debug为您的Car结构实现。这是一个适合您的解决方案.. 请注意// <----- parts我添加的所有内容(这里是在操场上):

#[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适当的地方使用来减少传递引用和生命周期的需要。在您的小示例中可能不那么重要,但随着代码变大,它们可能会变得棘手。

于 2016-08-24T03:28:50.033 回答