Rust 如何在闭包中传递捕获字符串,而不导致编译器错误?

Rust 如何在闭包中传递捕获字符串,而不导致编译器错误?,rust,closures,Rust,Closures,编译器对以下代码发出错误,我不知道如何修复它。注意,它适用于非闭包(直接调用)情况,仅当我尝试捕获闭包中的值s时,它才失败。解决这个问题的正确方法是什么 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 i

编译器对以下代码发出错误,我不知道如何修复它。注意,它适用于非闭包(直接调用)情况,仅当我尝试捕获闭包中的值
s
时,它才失败。解决这个问题的正确方法是什么

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);
}
fn计数字母(数据:字符串,c:char)->i32{
data.chars().filter(|x |*x==c).count()作为i32
}
fn main()
{
//假设这是一个字符串,即使在这个玩具示例中它可能是一个str
let s=“曾经有一个男人从南塔基特来”;
//工作
println!(“{:?}”,计数字母(s,'n');
//错误[E0507]:无法移出'FnMut'闭包中捕获的变量's'
let result:Vec=('a'..='z').map(|x |(x,count_字母(s.clone,x))).collect();
println!(“{:?}”,结果);
}

错误为:error[E0507]:无法移出
s
,这是
FnMut
闭包中捕获的变量

如果需要此行为:

fn count_letter(data : &str, 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'));
     
    // Also works
    let result : Vec<(char, i32)> = ('a'..='z').map(|x| (x, count_letter(&s, x))).collect();
    println!("{:?}", result);
}
fn计数字母(数据:&str,c:char)->i32{
data.chars().filter(|x |*x==c).count()作为i32
}
fn main()
{
//假设这是一个字符串,即使在这个玩具示例中它可能是一个str
let s=“曾经有一个男人从南塔基特来”;
//工作
println!(“{:?}”,计数字母(&s,'n');
//也有效
让结果为:Vec=('a'..='z').map(|x |(x,count_字母(&s,x))).collect();
println!(“{:?}”,结果);
}

println中的
count\u字母
取得字符串
s
的所有权。这就是为什么在这一点之后你不能使用它。(但是,您错过了
s.clone
的括号)。如果您在第一次使用
s
时添加另一个
.clone
,您的代码就可以了;)除非您确实需要
count\u letter
来获得字符串数据的所有权(因此需要不断克隆字符串),否则最好传递对字符串的引用: