You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
type annotation of closure args breaks borrow checking #100002
fnmain(){letmut list = vec![];letmut add_to_list = |name:_| {
list.push(name);};let name = String::from("name1");add_to_list(&name);}
but when a type annotation is added to the closure argument, it fails:
- let mut add_to_list = |name: _| {+ let mut add_to_list = |name: &str| {
Workaround
Sometimes type annotation is necessary when type inference fails. :
fnmain(){letmut list = vec![];letmut add_to_list = |name:_| {//ERROR type annotations neededif !name.is_empty(){
list.push(name);}};let name = String::from("name1");add_to_list(&name);}
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:
/// A closure that expects an argument of SOME specific lifetime, `'a`.typeFnSig1<'a> = dynFnMut(&'astr);/// A closure that expects an argument of ANY lifetime./// Aka higher-ranked lifetime.typeFnSig2 = dynfor<'a>FnMut(&'astr);
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:
I have written this be referenced when addressing the breakages of #98835. Because I found most breakages were users relying on #98589 as a workaround for this limitation with closures.
Activity
aliemjay commentedon Jul 31, 2022
I have written this be referenced when addressing the breakages of #98835. Because I found most breakages were users relying on #98589 as a workaround for this limitation with closures.
@rustbot label C-bug T-types A-closures A-lifetimes