Skip to content

behavior of '_ around dyn Trait is wrong #48468

Closed
@nikomatsakis

Description

@nikomatsakis

Generally speaking, '_ is equivalent to "eliding" a lifetime completely. That is, &'_ T and &T are equivalent, as are Foo<'_> and Foo (unfortunately). However, there are two cases where this is not true:

  • dyn Trait + '_ -- the object-lifetime-defaulting rules are different, and '_ needs to interact with them (same for Trait, of course)
  • impl Trait + '_ -- same, but for different reasons

@cramertj pointed out that our current behavior around dyn Trait is not what we really want:

#![feature(dyn_trait)]
#![feature(underscore_lifetimes)]

// These two give the same error that the iterator must be valid for the 'static lifetime:
fn a<T>(items: &[T]) -> Box<dyn Iterator<Item=&T>> {
    Box::new(items.iter()) //~ ERROR cannot infer an appropriate lifetime
}

fn b<T>(items: &[T]) -> Box<dyn Iterator<Item=&T> + '_> {
    Box::new(items.iter()) // *Should* be OK, currently errors
}

// But this one works:
fn c<'a, T>(items: &'a [T]) -> Box<dyn Iterator<Item=&'a T> + 'a> {
    Box::new(items.iter()) // OK
}

fn main() { }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-type-systemArea: Type systemT-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