Here is an example of some structs:
enum VehicleType {
Car,
Motorcycle,
}
struct Vehicle {
name: String,
horsepowers: i32,
vehicle_type: VehicleType,
}
struct Person<'a> {
vehicle: &'a Vehicle,
name: &'a str,
}
and in main function:
let mut car = Vehicle {
name: "Nissan GTR".to_string(),
horsepowers: 300,
vehicle_type: VehicleType::Car,
};
let alice = Person {
name: "Alice",
vehicle: &car, // Share a reference to the same car
};
let bob = Person {
name: "Bob",
vehicle: &car, // Share a reference to the same car
};
println!("{} drives {}", alice.name, alice.vehicle.name);
println!("{} drives {}", bob.name, bob.vehicle.name);
Now let's say we want to update the name of the car while preserving that Alice and Bob drive the same car
car.name = "Lamborghini".to_string();
car.horsepowers = 684;
println!("{} drives {}", alice.name, alice.vehicle.name);
println!("{} drives {}", bob.name, bob.vehicle.name);
This of course fails because car
is borrowed by both Alice and Bob.
Why wouldn't rust compiler allow this? How does this introduce memory safety issues? How to go about a pattern like this?