[SOLVED] Reference to struct that impl trait with lifetime


#1

hi,

I am trying to hold a a mut ref to a object that implements two traits and then implent methods on this:

struct test<'a, T: Read + Seak> {
    value: i32,
    object: &'mut T,
}

impl<'a, T: Read + Seek> test<'a, T> {
    pub fn new<T: Read + Seek>(object: T) -> io::Result<test<'a, T>,>  {
    ...
    }
}

but this does not compile through I have to admit that I just guessed the impl part. I do not realy understand if The lifetime or the traits have to go in the <> befor or after the struct name. Also do I also have to add this to the Result?


#2

The first thing to note is that because your impl already is generic over T, the method new doesn’t need to be:

pub fn new(object: T) -> io::Result<test<'a, T>> {...}

The second part is that you need to put a lifetime constraint on T to make sure that it lives at least as long as the reference &'a T that points to it. (The compiler actually tells you about this is a very clear manner.)

struct Test<'a, T: Read + Seek + 'a> {...}
impl<'a, T: Read + Seek + 'a> Test<'a, T> {...}

The third point is the following: As it stands, your method new takes object by value.
That means that at the end of new, object gets destroyed. Taking a reference to a value that will get destroyed immediately can’t work out.
That means you have to pass object by reference and make sure that it lives at least as long as the reference you want to take:

pub fn new(object: &'a T) -> io::Result<test<'a, T>> {...}

And finally, you can save some keystrokes by using Self instead of repeating the name of the type you are implementing. :slight_smile:

pub fn new(object: &'a T) -> io::Result<Self> {...}

Note that in this example, I used shared references to object. If you want to use a mutable, i.e. exclusive reference, you have to replace &'a with &'a mut.


#3

wow,

Thank you for the detailed explenation this helped :slight_smile: