Skip to content

have simpler diagnostic when passing arg to closure and missing borrow #64915

Closed
@matthiaskrgr

Description

@matthiaskrgr

playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9f1e00046f513d4d9da8790042e52ca9

Code:

struct MyStruct {
    age: u32
}

fn run<F: Fn(&MyStruct) -> bool>(func: F, data: &MyStruct) -> bool {
  func(&data)
} 

fn main() {
    let m = MyStruct { age: 4};
    let x = run(|x:MyStruct| x.age > 3, &m);
    println!("{}", x);
}

The error I got was

   Compiling playground v0.0.1 (/playground)
error[E0631]: type mismatch in closure arguments
  --> src/main.rs:12:13
   |
6  | fn run<F: Fn(&MyStruct) -> bool>(func: F, data: &MyStruct) -> bool {
   |    ---    --------------------- required by this bound in `run`
...
12 |     let x = run(|x:MyStruct| x.age > 3, &m);
   |             ^^^ ---------------------- found signature of `fn(MyStruct) -> _`
   |             |
   |             expected signature of `for<'r> fn(&'r MyStruct) -> _`

which is quite convoluted in my opinion.
It turned out I was only missing a borrow:
let x = run(|x:MyStruct| x.age > 3, &m);
=>
let x = run(|x:&MyStruct| x.age > 3, &m);

A simple "hint: add missing borrow: "&MyStruct"" with corresponding span would have been a lot more helpful here in my opinion.

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.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