Rust closures from factory functions

后端 未结 1 1149
醉话见心
醉话见心 2020-12-21 12:25

I have some Rust code I\'m trying to get working but I\'m not sure how to go about it.

fn main() {
    let names = vec![\"foo\", \"bar\", \"baz\"];
    let p         


        
相关标签:
1条回答
  • 2020-12-21 13:06

    The error says that names must outlive the static lifetime, this is because the boxed Fn has static lifetime. You have two options:

    1. Add the 'static lifetime to names:

      fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
          Box::new(move|| {
              // ...
          })
      }
      
    2. Change the lifetime of the boxed Fn to match the names lifetime:

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

    Note that the body of closure needs to be adjusted and that you are giving the ownership of names to printer, so you cannot use names in do_other_thing. Here is a fixed version:

    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()
        })
    }
    
    0 讨论(0)
提交回复
热议问题