Skip to content

Confusing compiler error for function taking closure returning reference #91966

Open
@mgejke

Description

@mgejke

Compiling the following code:

use std::collections::HashMap;

fn unclear_compiler_error(f: &dyn Fn(&i32) -> Option<&i32>) -> i32 {
    242
}

fn main() {
    let map: HashMap<i32, i32> = HashMap::new();

    let f = |p: &i32| match map.get(&p) {
        Some(v) => Some(v),
        _ => None,
    };
    unclear_compiler_error(&f);
}

Gives the following output:

error[E0308]: mismatched types
  --> src/compiler/main.rs:14:28
   |
14 |     unclear_compiler_error(&f);
   |                            ^^ one type is more general than the other
   |
   = note: expected enum `Option<&i32>`
              found enum `Option<&i32>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `thing` due to previous error

But I think the actual issue is with lifetimes, changing to Option<i32> makes it compile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsD-confusingDiagnostics: Confusing error or lint that should be reworked.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler 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