工厂功能的防锈罩

松软的

我有一些Rust代码,我想开始工作,但不确定如何去做。

fn main() {
    let names = vec!["foo", "bar", "baz"];
    let print = printer(names);
    let result = print();
    println!("{}", result);
    do_other_thing(names.as_slice());
}

fn printer(names: Vec<&str>) -> Box<Fn() -> String> {
    Box::new(move || {
        let text = String::new();
        for name in names {
            text = text + name;
        }
        text
    })
}

fn do_other_thing(names: &[&str]) {}

编译为:

error[E0477]: the type `[closure@src/main.rs:10:14: 16:6 names:std::vec::Vec<&str>]` does not fulfill the required lifetime
  --> src/main.rs:10:5
   |
10 |       Box::new(move || {
   |  _____^ starting here...
11 | |         let text = String::new();
12 | |         for name in names {
13 | |             text = text + name;
14 | |         }
15 | |         text
16 | |     })
   | |______^ ...ending here
   |
   = note: type must outlive the static lifetime

我对发生的事情有一个模糊的想法。闭包似乎有可能超过该names参数。我可以注释为,'static但是感觉不正确,即使那样,我也希望不要移动矢量以使其do_other_thing起作用。我需要以某种方式复制。

清算

该错误表明names必须超过静态寿命,这是因为盒装Fn具有静态寿命。您有两种选择:

  1. 'static生存期添加names

    fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
        Box::new(move|| {
            // ...
        })
    }
    
  2. 更改盒装Fnnames寿命以匹配寿命:

    fn printer<'a>(names: Vec<&'a str>) -> Box<Fn() -> String + 'a>{
        Box::new(move|| {
            // ...
        })
    }
    

请注意,需要调整闭包的主体,并且您要赋予namesto的所有权printer,因此不能names在中使用do_other_thing这是固定版本:

fn main() {
    let names = vec!["foo", "bar", "baz"];
    let print = printer(&names);
    let result = print();
    println!("{}", result);
    do_other_thing(names.as_slice());
}

fn printer<'a>(names: &'a Vec<&str>) -> Box<Fn() -> String + 'a>{
    Box::new(move || {
        // this is more idiomatic
        // map transforms &&str to &str
        names.iter().map(|s| *s).collect()
    })
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章