Dereference a generic-type value of struct

struct Example<T>(T);

impl<T> Drop for Example<T> {
    fn drop(&mut self) {
        func(self.0);
    }
}

fn func<T>(x: T) {
    // println!("{}", x);
}

fn main() {
    let mut x = Example(5);
    x = Example(6);
}

Returns:

move occurs because `self.0` has type `T`, which does not implement the `Copy` trait

In general you cannot get a T from a &mut Example<T>, which is what you are trying to do here. But when T: Default you can use std::mem::take, or if you have some other way to construct a "throwaway" T value you can plug it into the closely-related std::mem::replace.

impl<T: Default> Drop for Example<T> {
    fn drop(&mut self) {
        func(std::mem::take(self.0));
        // or `func(std::mem::replace(self.0, some_throwaway_value));`
    }
}

Also of course if T: Clone then you can do func(self.0.clone()).

If none of those approaches work for you, you will have to see if you can rewrite func to take &mut T instead.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.