Skip to content

Lifetime error with associated types, methods, and type aliases. #22356

Closed
@brendanzab

Description

@brendanzab

Sorry, I couldn't think up a better name for this issue. It popped up in gfx-rs/gfx#564.

pub struct Handle<T, I>(T, I);

impl<T, I> Handle<T, I> {
    pub fn get_info(&self) -> &I {
        let Handle(_, ref info) = *self;
        info
    }
}

pub struct BufferHandle<D: Device, T> {
    raw: RawBufferHandle<D>,
}

impl<D: Device, T> BufferHandle<D, T> {
    pub fn get_info(&self) -> &String {
        self.raw.get_info()
    }
}

pub type RawBufferHandle<D: Device> = Handle<<D as Device>::Buffer, String>;

pub trait Device {
    type Buffer;
}

<anon>:16:9: 16:17 error: the associated type `<D as Device>::Buffer` may not live long enough [E0311]
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
<anon>:16:9: 16:17 help: consider adding an explicit lifetime bound for `<D as Device>::Buffer`
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
<anon>:15:39: 17:6 note: the associated type `<D as Device>::Buffer` must be valid for the anonymous lifetime #1 defined on the block at 15:38...
<anon>:15     pub fn get_info(&self) -> &String {
<anon>:16         self.raw.get_info()
<anon>:17     }
<anon>:16:9: 16:17 note: ...so that the reference type `&Handle<<D as Device>::Buffer, collections::string::String>` does not outlive the data it points at
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
<anon>:16:9: 16:17 error: the associated type `<D as Device>::Buffer` may not live long enough [E0311]
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
<anon>:16:9: 16:17 help: consider adding an explicit lifetime bound for `<D as Device>::Buffer`
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
<anon>:15:39: 17:6 note: the associated type `<D as Device>::Buffer` must be valid for the anonymous lifetime #1 defined on the block at 15:38...
<anon>:15     pub fn get_info(&self) -> &String {
<anon>:16         self.raw.get_info()
<anon>:17     }
<anon>:16:9: 16:17 note: ...so that the reference type `&Handle<<D as Device>::Buffer, collections::string::String>` does not outlive the data it points at
<anon>:16         self.raw.get_info()
                  ^~~~~~~~
error: aborting due to 2 previous errors

Moving the implementation of Handle::get_info into BufferHandle::get_info seems to fix the problem:

impl<D: Device, T> BufferHandle<D, T> {
    pub fn get_info(&self) -> &String {
        let Handle(_, ref info) = self.raw;
        info
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-borrow-checkerArea: The borrow checker

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions