0

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.

Mr User
  • 205
  • 1
  • 5
  • This is a rather broad question. There are many ways of achieving shared multiple access in safe code, and it really depends on your use case which way is best. For this simple question, the easiest solution are [atomic integers](https://doc.rust-lang.org/std/sync/atomic/#structs), which can be modified through shared references. In other cases, the solution is a `Cell`, or a `RefCell`, or a `Mutex`. And in really complex cases, you want an entity component system like the Bevy ECS. – Sven Marnach Mar 24 '23 at 14:28
  • 1
    While this question focuses on `Arc` all the soluttions also apply to regular shared references: [How do I share a mutable object between threads using Arc?](https://stackoverflow.com/questions/31373255/how-do-i-share-a-mutable-object-between-threads-using-arc) – cafce25 Mar 24 '23 at 14:29

0 Answers0