type annotation of closure args breaks borrow checking #100002
Labels
A-closures
Area: Closures (`|…| { … }`)
A-lifetimes
Area: Lifetimes / regions
C-bug
Category: This is a bug.
T-types
Relevant to the types team, which will review and decide on the PR/issue.
This example compiles as expected:
but when a type annotation is added to the closure argument, it fails:
Workaround
Sometimes type annotation is necessary when type inference fails. :
In this case you can use this ugly hack to annotate the type in the closure body:
let mut add_to_list = |name: _| { + let name: &str = name; // hack: annotate the type here to avoid rustc bug #xxx if !name.is_empty() {
But why?
When rustc encounters such closure, It has to pick up one of these two types for the closure:
We want the first one here but the compiler is not smart enough to infer this. Instead it follows a set of dumb rules1 that leads it to the second type, and then it fails when borrow-checking the closure for the same reason the following fails:
There is a promising work on a-mir-fomality to make this inference smarter.
Footnotes
simply if the lifetime appears in type annotation, it's inferred to be higher-ranked ↩
The text was updated successfully, but these errors were encountered: