I'm working with a bit of complex (to me, atleast) code which I can't figure out. I've distilled my problem in the code below. In my actual code the reason I use Arc and Mutex is because I'm working with threads. The reason for the GuestState enum is that I would like to add different types of guests in the future without changing implementation of existing guests.
use std::sync::{Arc, Mutex};
enum GuestState {
VIP(VIPState)
}
struct VIPState {
name: String,
something: bool,
}
fn main() {
// This happens when program first starts
let mut guest_state_mutexes: Vec<Arc::<Mutex<GuestState>>> = vec![];
let state_mutex = Arc::new(Mutex::new(GuestState::VIP(VIPState {
name: "Abc".to_string(),
something: true,
})));
guest_state_mutexes.push(state_mutex);
// This happens later in a different thread which has
// to modify information inside a VIPState
let mutex_for_use = guest_state_mutexes.get(0).unwrap();
let state = mutex_for_use.lock().unwrap();
match *state { // PROBLEM
GuestState::VIP(mut vip) => {
vip.something = false;
},
}
}
If I don't deference the PROBLEM-row, I get an error saying types are mismatched, GuestState
does not match MutexGuard<'_, GuestState>
. If I explicitly deference state
then I get an error saying VIPState
does not implement Copy
and implementing Copy is not possible because String
is involved.
Is there an easy solution to this or am I approching this in a wrong way? I hope there is enough information to make educated guesses.