Skip to content

Const closure weirdness #55272

Closed
Closed

Description

@DutchGhost

The following compiles just fine:

#![feature(impl_trait_in_bindings)]
fn main() {
    let func: impl Fn(&str) -> usize = |s| s.parse().unwrap();

}

However this does not:

#![feature(impl_trait_in_bindings)]

fn main() {
    const func: impl Fn(&str) -> usize = |s| s.parse().unwrap();
}

It gives the following error message:

error: non-defining existential type use in defining scope
 --> src/main.rs:4:42
  |
4 |     const func: impl Fn(&str) -> usize = |s| s.parse().unwrap();
  |                                          ^^^^^^^^^^^^^^^^^^^^^^ lifetime `` is part of concrete type but not used in parameter list of existential type

error: aborting due to previous error

error: Could not compile `playground`.

Why is this an error? The closure does not capture anything, so it's lifetime is 'static, and const requires 'static.

Activity

  1. ExpHP commented on Oct 22, 2018

    @ExpHP
    Contributor

    Note also that the following works:

    #![feature(impl_trait_in_bindings)]
    fn main() {
        const func: impl Fn(String) -> usize = |s| s.parse().unwrap();
    }

    so it has something to do with the &str type parameter. But the trick that often fixes problems like this in other places in rust does not help here:

    #![feature(impl_trait_in_bindings)]
    fn main() {
        // explicitly annotate the closure arg as &_.
        // same error as OP
        const func: impl Fn(&str) -> usize = |s: &_| s.parse().unwrap();
    
        // not even this helps
        const func: impl for<'a> Fn(&'a str) -> usize = |s: &_| s.parse().unwrap();
    }
  2. added
    A-lifetimesArea: Lifetimes / regions
    A-closuresArea: Closures (`|…| { … }`)
    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)
    on Oct 25, 2018
  3. ilyvion commented on Oct 1, 2022

    @ilyvion

    Seems this feature doesn't even exist anymore.

  4. traviscross commented on Apr 28, 2025

    @traviscross
    Contributor

    We can close this as the feature was pulled out in #86729 and what was added back in #134185 only supports local bindings.

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

    A-closuresArea: Closures (`|…| { … }`)A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-lifetimesArea: Lifetimes / regionsF-impl_trait_in_bindings`#![feature(impl_trait_in_bindings)]`

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions