Problem with lifetime of Box

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.

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 Learning Rust With Entirely Too Many Linked Lists as a tutorial for linked list related lifetime issues :slight_smile:

2 Likes

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.

1 Like

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.

Thanks a lot.