Skip to content

Unhelpful error message when associated type needs lifetime annotation #20685

@seanmonstar

Description

@seanmonstar

Chopped code that shows this error:

fn with_connector<C: NetworkConnector>(connector: &mut C) -> HttpResult<Request> {
    let stream = try!(connector.connect(host, port, scheme));
    let stream = BufferedWriter::new(box stream as Box<NetworkStream + Send>);
    //                               ^~~ parameter `C` may not live long enough, consider an explicit lifetime 'static
}

pub trait NetworkConnector {
    type Stream: NetworkStream + Send;

    pub fn connect(...) -> IoResult<Self::Stream>;
}

Code fixed. Note that the lifetime wasn't need on C, though the error message says it was.

fn with_connector<'a, C: NetworkConnector<Stream = T>, T: NetworkStream+'a>(connector: &C) -> Result<Box<NetworkStream + 'a>, ()> {
    let stream = try!(connector.connect());
    Ok(box stream as Box<NetworkStream + 'a>)
}

trait NetworkStream {}

pub trait NetworkConnector {
    type Stream: NetworkStream;

    fn connect(&self) -> Result<Self::Stream, ()>;
}

/cc @nick29581

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions