3

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).

porton
  • 5,214
  • 11
  • 47
  • 95
  • 1
    The `MutexGuard` in the struct shouldn't be a reference, it should be just `MutexGuard<'a, ()>`, otherwise you're returning a reference to a local variable which just can't work. But even after making this change, `guard` is pointing inside `mutex`, so you're effectively creating a self-referential data structure, and that won't compile. The only way for that to work is using unsafe. – user4815162342 Jan 21 '22 at 19:57
  • @user4815162342 How to use `unsafe` in this situation? – porton Jan 21 '22 at 20:03
  • https://crates.io/crates/lockpool solves my real problem. – porton Jan 21 '22 at 20:09
  • Does lockpool then answer your question? You can take a look at how they use unsafe, but there are probably other approaches. – user4815162342 Jan 21 '22 at 20:16
  • Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – Colonel Thirty Two Jan 21 '22 at 21:59

0 Answers0