Skip to content

Hidden type for impl trait captures lifetime when it's not supposed to #108512

Closed
@PixelDust22

Description

@PixelDust22

I tried this code:

trait MyTrait {
}
struct MyTraitStruct;
impl MyTrait for MyTraitStruct {

}
fn inner<F>(writer: F) -> impl MyTrait + 'static
where F: FnOnce(&mut [u8])  {
    MyTraitStruct
}
fn outer(data: &[u8]) -> impl MyTrait + 'static {
    inner(|dst| {
        dst.copy_from_slice(data)
    })
}

I expected to see this compile.

Instead, I get this error:

error[E0700]: hidden type for `impl MyTrait + 'static` captures lifetime that does not appear in bounds
   --> core\src\pipeline\sbt.rs:222:5
    |
221 |   fn outer(data: &[u8]) -> impl MyTrait + 'static {
    |                  ----- hidden type `impl MyTrait + 'static` captures the anonymous lifetime defined here
222 | /     inner(|dst| {
223 | |         dst.copy_from_slice(data)
224 | |     })
    | |______^

For more information about this error, try `rustc --explain E0700`.

The writer argument is just a impl FnOnce(&mut [u8]) with no lifetime bounds.
The lifetime there is a HRTB, the full trait def is for<'a> FnOnce(&'a mut [u8])
It says the closure needs to accept any mutable byte slice, regardless of the slices lifetime.
It should have no impact on the lifetime of the closure.

Meta

rustc --version --verbose:

rustc 1.69.0-nightly (34e6673a0 2023-02-25)
binary: rustc
commit-hash: 34e6673a0473e90ef01a18eb575392c9e3859747
commit-date: 2023-02-25
host: x86_64-pc-windows-msvc
release: 1.69.0-nightly
LLVM version: 15.0.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions