Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

rust - How do I pass a capture a string in a closure without causing a compiler error?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I gues you want this behavior:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...