Skip to content

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

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

Activity

  1. added
    needs-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triaging
    on Apr 26, 2024
  2. ryanavella commented on Apr 27, 2024

    @ryanavella

    It compiles on nightly if you add #![feature(lifetime_capture_rules_2024)], so this is probably the expected (if surprising) behavior of lifetime capture rules in return-position impl Traits. At least until the 2024 edition.

    Related: #117587, rust-lang/rfcs#3498

  3. added
    T-typesRelevant to the types team, which will review and decide on the PR/issue.
    and removed
    needs-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triaging
    on May 10, 2024
  4. compiler-errors commented on Jan 3, 2025

    @compiler-errors
    Contributor

    Nightly suggests adding + use<'_, 'a>, so I think this is fixed.

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

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