Joey
Joey

Reputation: 215

object does not live long enough when implementing the `From` trait

My code has a '... does not live long enough error' error when I implement the From<T> trait for FileSlice, because the FlieSlice reference to the argument of the from method, and the argument dropped when the method returned.

Is there some way the solve this problem? Thank you.

struct FileSlice {
    data: Box<dyn FileHandle>,
}

trait FileHandle {
    fn read(&self, range: Range<usize>);
}

impl FileHandle for &'static [u8] {
    fn read(&self, range: Range<usize>) {
        let a = &self[range];
        println!("{:?}", a);
    }
}

impl<T> From<T> for FileSlice
where
    T: Deref<Target = [u8]> + 'static,
{
    fn from(a: T) -> Self {
        let b: &'static [u8] = a.deref(); //error: 'a' does not live long enough.
        FileSlice { data: Box::new(b) }
    }
}

Upvotes: 0

Views: 73

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70910

Deref::deref() has the signature:

fn deref(&self) -> &Self::Target

Or, desugared:

fn deref<'a>(&'a self) -> &'a Self::Target

It borrows self, and returns a reference with the same lifetime. Because of that, if you want the resulting reference to be 'static, you need &self to be &'static self. T: 'static is not related: it means self is static, but &self is the address of the parameter a, which is obviously not 'static. What you need is:

impl<T> From<&'static T> for FileSlice
where
    T: Deref<Target = [u8]>,
{
    fn from(a: &'static T) -> Self {
        let b: &'static [u8] = a.deref();
        FileSlice { data: Box::new(b) }
    }
}

Upvotes: 4

Related Questions