Skip to content

Trait methods can return &T types without lifetimes #8841

Closed
@erickt

Description

@erickt

It doesn't seem to matter whether or not an abstract trait method returns a &T type without a region:

trait A {
    fn foo(&self) -> ∫
}

struct B {
    x: int,
}

/*
impl A for B {
    fn foo(&self) -> &int { &self.x }
}
*/

fn main() {
}

Compiles fine. However, once impl A for B is uncommented, it properly errors with:

foo.rs:2:28: 2:40 error: cannot infer an appropriate lifetime due to conflicting requirements
foo.rs:2     fn foo(&self) -> &int { self.bar() }
                                     ^~~~~~~~~~~~
foo.rs:2:26: 2:40 note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 2:26...
foo.rs:2     fn foo(&self) -> &int { self.bar() }
                                   ^~~~~~~~~~~~~~
foo.rs:2:28: 2:33 note: ...due to the following expression
foo.rs:2     fn foo(&self) -> &int { self.bar() }
                                     ^~~~~
foo.rs:2:26: 2:40 note: but, the lifetime must be valid for the anonymous lifetime #2 defined on the block at 2:26...
foo.rs:2     fn foo(&self) -> &int { self.bar() }
                                   ^~~~~~~~~~~~~~
foo.rs:2:28: 2:40 note: ...due to the following expression
foo.rs:2     fn foo(&self) -> &int { self.bar() }
                                     ^~~~~~~~~~~~

What's interesting is that the impl cannot correct for the error in the trait. Changing it to this:

impl A for B {
    fn foo<'a>(&'a self) -> &'a int { &self.x }
}

Results in this error:

foo.rs:10:4: 10:47 error: method `foo` has an incompatible type: expected concrete lifetime, but found bound lifetime parameter &
foo.rs:10     fn foo<'a>(&'a self) -> &'a int { &self.x }
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I feel we should error out on the trait method or else we risk someone creating an unimplementable trait.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions