Skip to content

impl Trait return value infers 'static lifetime #51282

Closed
@HMPerson1

Description

@HMPerson1

This code (playground):

struct Foo {
    v: Vec<u8>
}

impl Foo {
    fn bar(&self) -> impl Iterator<Item=u8> {
        self.v.iter().cloned()
    }
}

fails to compile with:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
 --> src/main.rs:7:16
  |
7 |         self.v.iter().cloned()
  |                ^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     fn bar(&self) -> impl Iterator {
7 | |         self.v.iter().cloned()
8 | |     }
  | |_____^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:7:9
  |
7 |         self.v.iter().cloned()
  |         ^^^^^^
  = note: but, the lifetime must be valid for the static lifetime...
note: ...so that return value is valid for the call
 --> src/main.rs:6:22
  |
6 |     fn bar(&self) -> impl Iterator<Item=u8> {
  |                      ^^^^^^^^^^^^^^^^^^^^^^

Replacing impl Iterator with an explicit type works:

fn bar(&self) -> std::iter::Cloned<std::slice::Iter<u8>> {
    self.v.iter().cloned()
}

Explicitly bounding the output lifetime also works:

fn bar<'a>(&'a self) -> impl Iterator<Item=u8> + 'a {
    self.v.iter().cloned()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions