Skip to content

Unexpected "the parameter type T may not live long enough" at a point where T is not relevant #80675

Description

@SamRodri

This code fails to compile at the Box::new(foo) line with error[E0310]: the parameter type `B` may not live long enough.

My understanding is that at that point we have a variable of type {impl Foo} and Foo: 'static. If we move the boxing code
to a function (box_foo) the code compiles.

#![allow(unused)]

trait Foo: 'static { }

struct FooImpl;
impl Foo for FooImpl { }

trait Bar { }

struct Zing<B> { bar: B }
impl<B: Bar> Zing<B> {
    fn foo(self) -> impl Foo {
        FooImpl
    }

    fn foo_boxed(self) -> Box<dyn Foo> {
        let foo = self.foo();
        Box::new(foo)
        //box_foo(foo)
    }
}

fn box_foo(foo: impl Foo) -> Box<dyn Foo> {
    Box::new(foo)
}
error[E0310]: the parameter type `B` may not live long enough
  --> src/lib.rs:18:9
   |
11 | impl<B: Bar> Zing<B> {
   |      -- help: consider adding an explicit lifetime bound...: `B: 'static +`
...
18 |         Box::new(foo)
   |         ^^^^^^^^^^^^^ ...so that the type `impl Foo` will meet its required lifetime bounds

(Playground)

The compiler suggestion works, but adds an unwanted constrain on the bar field. The struct may want to build a 'static value from a non-static reference.

rustc --version --verbose:

rustc 1.49.0 (e1884a8e3 2020-12-29)
binary: rustc
commit-hash: e1884a8e3c3e813aada8254edfa120e85bf5ffca
commit-date: 2020-12-29
host: x86_64-pc-windows-msvc
release: 1.49.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-lifetimesArea: Lifetimes / regionsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions