Problem with lifetime of Box


#1

I want to make a function that return a pointer to data declared by Box type like this:

struct Type<T> {
        x: T,
    }

    struct Point<T> {
        point: Box<Type<T>>,
    }

    impl<T> Point<T> {
        fn get(self) ->  &Type<T> {
            self.point.as_ref()
        }
    }

The error message is:

error: missing lifetime specifier [E0106]
exam49.rs:12         fn get(self) ->  &Type<T> {
                                      ^~~~~~~~

I want to know how to declare lifetime explicitly with Box type or it really don’t need? and another question is that: I really want the function to return Box, a pointer only can point to data declared by Box pointer, but when I try like this:

let a = Box::new( Type{x: 2} );
return &*a; // or return a.as_ref();

But return type is &Type. How can I return Box pointer?
I meet this problem when I try to write some data structure like link list and I want to get a pointer that point some node of link list for insert or delete operation.


#2

This should work:

impl<T> Point<T> {
    fn get(&self) -> &Type<T> {
        self.point.as_ref()
    }
}

Or, with explicitly declared lifetimes:

impl<T> Point<T> {
    fn get(&'a self) -> &'a Type<T> {
        self.point.as_ref()
    }
}

Also I would recommend http://cglab.ca/~abeinges/blah/too-many-lists/book/ as a tutorial for linked list related lifetime issues :slight_smile:


#3

To continue on matklad’s fix, the problem is that that by passing “self” into the get method, it means that Point is being destroyed when the function returns. By changing it to a &self, the Point object doesn’t get destroyed at the end of the function, since it was only borrowed, and the reference to point is valid.


#4

Thanks, I ever thought that Box is pointer type so that I didn’t borrow it, but I forgot that I moved it. And thanks for your recommendation.


#5

Thanks a lot.