When I wrote the Gobang program, I found that I could not modify the game state(&mut self) while passing the immutable reference of the game to the display instance and the algorithm instance. Because this will result in one mutable reference and multiple immutable references.
However, when I move the game instance into the display instance, and let the display instance be responsible for modifying the game state and giving the immutable reference of the game instance. I found that I can give immutable references while modifying the game state. Does this mean that there is one mutable reference and multiple immutable references at the same time? Further, is this implementation concurrency safe?
The following is the runnable Code:
struct Game {
a: i32,
}
struct Display {
game: Game,
}
impl Display {
fn new(game: Game) -> Self {
Display { game }
}
fn change_game(&mut self) {
self.game.a += 1;
}
fn give_a_immutable_ref(&self) -> &Game {
&self.game
}
}
fn main() {
let game = Game { a: 0 };
let mut display = Display::new(game);
// game loop
for i in 0..4 {
display.change_game();
println!("{}", display.give_a_immutable_ref().a);
}
}
The following is the code that failed to compile:
struct Game {
a: i32,
}
impl Game {
fn change_a(&mut self) {
self.a += 1;
}
}
struct Display<'a> {
game: &'a Game,
}
impl<'a> Display<'a> {
fn new(game: &'a Game) -> Self {
Display { game }
}
fn give_a_immutable_ref(&self) -> &Game {
&self.game
}
}
fn main() {
let mut game = Game { a: 0 };
let display = Display::new(&game);
for i in 0..4 {
game.change_a();
println!("{}", display.give_a_immutable_ref().a);
}
}