Cannot Move Inner Value out of an Arc Rust

Viewed 952

I'm trying to retrieve the inner value of an Arc Mutex wrapper around an FLTK-RS Widget:

pub struct ArcWidget<T: Clone + WidgetExt + WidgetBase>(Arc<Mutex<T>>);


impl<T: Clone + WidgetExt + WidgetBase> ArcWidget<T>{    
    pub fn widg(&self)->T{
        let lock = self.0.clone();
        let lock2 = lock.into_inner().unwrap();
        lock2
    }
    pub fn redraw(&self){
        let mut widg = self.0.lock().unwrap();
        widg.redraw();
    }
}

However this results in error:

let lock = self.0.into_inner().unwrap().clone(); 
cannot move out of an `Arc` - move occurs because value has type `Mutex<T>`, which does not implement the `Copy` trait

I thought adding the Clone trait restriction would solve this, but apparently it did not. How might I address this error? WidgetExt+WidgetBase are incompatible with Copy, so I can not add a Copy trait restriction.

1 Answers

For pub fn widg(&self) -> T { to work, it would be necessary to make a full clone of the T value. W ith all the bounds in your question, that would look like this:

pub fn widg(&self) -> T {
    self.0.lock().unwrap().clone()
}

but that is very unlikely to be what you actually want. It seems like what you probably actually want is this:

pub fn widg(&self) -> &Mutex<T> {
    &self.0
}

because then code anywhere can do

let mut widg = self.widg().lock().unwrap();
widg.redraw();

or call any other method on the inner widget.

Related