Here are some demo codes:
struct State{
x: i32
}
impl State {
fn new() -> Self{
Self {x:0}
}
fn plusplus(&mut self){
self.x += 1
}
}
struct Hello<'a>{
s: &'a mut State
}
impl Hello<'_>{
fn hello(&mut self){
println!("hello");
self.s.plusplus();
}
}
struct Hi<'a>{
s: &'a mut State
}
impl Hi<'_>{
fn hi(&mut self){
println!("hi");
self.s.plusplus();
}
}
fn main() {
let mut s = State::new();
let mut a = Hello{s:&mut s};
let mut b = Hello{s:&mut s};
a.hello();
a.hello();
}
The idea is that we have two structs Hello
and Hi
, and when a method of any one of them is called, we increment the central count in s
by 1.
The code does not compile because we cannot borrow s
as mutable twice.
My question is: what are some good way to fix the code? Must I use the unsafe
keyword?
I am a bit reluctant to use the unsafe
keyword, because this is such a simple situation, and by using a lock, the possibility of racing conditions can easily be eliminated.