The compiler issues an error on the following code, and I don't know how to fix it. Note, it works for the non-closure (direct call) case, it's just when I try to capture the value s
in a closure that it fails. What's the right way to fix this?
fn count_letter(data : String, c : char) -> i32 {
data.chars().filter(|x| *x == c).count() as i32
}
fn main()
{
// Pretend this has to be a String, even though in this toy example it could be a str
let s = "there once was a man from nantucket".to_string();
// Works
println!("{:?}", count_letter(s, 'n'));
// error[E0507]: cannot move out of `s`, a captured variable in an `FnMut` closure
let result : Vec<(char, i32)> = ('a'..='z').map(|x| (x, count_letter(s.clone, x))).collect();
println!("{:?}", result);
}
The error is: error[E0507]: cannot move out of s
, a captured variable in an FnMut
closure
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…