I am trying to return a struct containing reference to a shared mutex:
struct Test<'a> {
mutex: Arc<Mutex<()>>,
guard: &'a MutexGuard<'a, ()>,
}
impl<'a> Test<'a> {
pub fn new() -> Self {
let mutex = Arc::new(Mutex::new(()));
let guard = &mutex.lock().unwrap();
Self {
mutex,
guard,
}
}
}
The lifetimes seem correct: the mutex exists at least during the lifetime of Test
, so MutexGuard
does not have a stalled reference to mutex. But Rust gives errors. How to explain to Rust that the lifetime of mutex
field is enough long for guard
to work well?
cannot return value referencing local variable `mutex`
returns a value referencing data owned by the current function
BTW, I am trying to create a "mutli-mutex" - a set of mutexes for keys (like as in HashMap
), to block downloading a file whose name is in hashmap (because it is already downloading).