Skip to content

impl FnOnce hidden type captures more than the closure itself #124413

Closed
@kuviman

Description

@kuviman

I tried this code:

trait FooTrait {}

struct Foo<'a> {
    value: i32,
    x: &'a mut dyn FooTrait,
}

impl<'a> Foo<'a> {
    fn works(&self) -> Box<dyn FnOnce() -> i32 + '_> {
        Box::new(|| self.value)
    }
    fn doent(&self) -> impl FnOnce() -> i32 + '_ {
        || self.value
    }
}

I expected both methods to compile, but only the dyn version does.

The error says:

error[E0700]: hidden type for `impl FnOnce() -> i32 + '_` captures lifetime that does not appear in bounds
  --> src/lib.rs:13:9
   |
8  | impl<'a> Foo<'a> {
   |      -- hidden type `{closure@src/lib.rs:13:9: 13:11}` captures the lifetime `'a` as defined here
...
12 |     fn doent(&self) -> impl FnOnce() -> i32 + '_ {
   |                        ------------------------- opaque type defined here
13 |         || self.value
   |         ^^^^^^^^^^^^^

The error says that the closure captures lifetime 'a, although the closure in the dyn version is the same and compiles successfully without capturing 'a

Tried both current stable and nightly

playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.F-lifetime_capture_rules_2024`#![feature(lifetime_capture_rules_2024)]`T-typesRelevant to the types 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