New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

existential impl Trait gets seriously confused about lifetimes, "impl T + 'static" does not satisfy static lifetime #53791

Closed
khuey opened this Issue Aug 29, 2018 · 3 comments

Comments

Projects
None yet
2 participants
@khuey
Copy link
Contributor

khuey commented Aug 29, 2018

This is simplified from some real code I have.

use std::borrow::BorrowMut;
use std::marker::PhantomData;

trait T {}

impl<X> T for Box<X> where X: T {}

struct S<'a> {
    phantom: PhantomData<&'a u32>,
}

struct U;

impl T for U {}

fn f1<'a, R>(_: R) -> impl T + 'static
    where R: BorrowMut<S<'a>>
{
    let f = Box::new(U);
    f
}

fn f2<'a>(s: S<'a>) -> impl T + 'static {
    f1::<S<'a>>(s)
}

fn f1_boxed<'a, R>(_: R) -> Box<T>
    where R: BorrowMut<S<'a>>
{
    let f = Box::new(U);
    f
}

fn f2_boxed<'a>(s: S<'a>) -> Box<T> {
    f1_boxed::<S<'a>>(s)
}

The boxed versions compile fine, but the impl Trait version fails with

error[E0477]: the type `impl T` does not fulfill the required lifetime
  --> src/lib.rs:23:24
   |
23 | fn f2<'a>(s: S<'a>) -> impl T + 'static {
   |                        ^^^^^^^^^^^^^^^^
   |
   = note: type must satisfy the static lifetime

I see this on both stable and 1.30.0-nightly (7061b27 2018-08-28).

@estebank

This comment has been minimized.

Copy link
Contributor

estebank commented Aug 29, 2018

I'm not sure if the compiler is supposed to be accepting this code to begin with.

With NLL enabled, the diagnostic is slightly more illuminating:

error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
  --> src/lib.rs:25:24
   |
25 | fn f2<'a>(s: S<'a>) -> impl T + 'static {
   |                        ^^^^^^^^^^^^^^^^
   |
note: hidden type `impl T` captures the lifetime 'a as defined on the function body at 25:7
  --> src/lib.rs:25:7
   |
25 | fn f2<'a>(s: S<'a>) -> impl T + 'static {
   |       ^^

Changing either the return type to impl T + 'a or the argument type to 'static makes the compile succeed.

@khuey

This comment has been minimized.

Copy link
Contributor Author

khuey commented Aug 29, 2018

Sure, but the return value doesn't actually depend on the lifetime 'a.

@khuey

This comment has been minimized.

Copy link
Contributor Author

khuey commented Aug 29, 2018

@mbrubeck says this is #42940

@khuey khuey closed this Aug 29, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment