0

Here is the code:

pub struct ForesterViewModel {
    m_tree_lines: Arc<Mutex<Vec<TreeLine>>>,
}

impl ForesterViewModel {
    pub fn new() -> ForesterViewModel {
        ForesterViewModel {
            m_tree_lines: Arc::new(Mutex::new(vec![])),
        }
    }

    pub fn get_the_forest(&mut self) -> &mut Vec<TreeLine> {
        ???????????????????????????????
    }
}

I need help writing the get_the_forest function. I've tried many various things but they all return compilation errors. I need to return a mutable reference to Vec<TreeLine> which is warpped behind an Arc and a Mutex in self.m_tree_lines.

Help please :-)

Refael Sheinker
  • 383
  • 4
  • 13
  • 3
    You can't really do this. The whole point of `Mutex` is that you lock the data inside and prevent it from being accessed until the reference to it is dropped. This is accomplished by forcing the data to be access through a [`MutexGuard`](https://doc.rust-lang.org/std/sync/struct.MutexGuard.html). – Aplet123 Mar 20 '21 at 21:05
  • 1
    why don't you return the mutex guard ? – Stargateur Mar 20 '21 at 21:06
  • 1
    https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=12fd19d7ab48f2fb002fc3d936bf1f4c – Stargateur Mar 20 '21 at 21:14
  • @Aplet123 I see you point and I understand. Followup question: if I change the return value to be immutable, `&Vec`, would it be possible then? – Refael Sheinker Mar 20 '21 at 21:39
  • 2
    Does this answer your question? [Mutable borrow to object inside Mutex - how to refactor?](https://stackoverflow.com/questions/59069382/mutable-borrow-to-object-inside-mutex-how-to-refactor) or perhaps [How to return a reference to a sub-value of a value that is under a mutex?](https://stackoverflow.com/questions/40095383/how-to-return-a-reference-to-a-sub-value-of-a-value-that-is-under-a-mutex) – kmdreko Mar 21 '21 at 03:21
  • 2
    @RefaelSheinker the reference being immutable doesn't help. *No* references can refer to the inner value of the Mutex without keeping the guard, that's now it knows its safe to be unlocked elsewhere. – kmdreko Mar 21 '21 at 03:24
  • Thank you all who helped. I now understand. – Refael Sheinker Mar 23 '21 at 21:03

0 Answers0