2016-08-03 6 views
1

私は錆のコードを持っています。私は仕事をしようとしていますが、どうすればいいか分かりません。工場機能からの錆止め

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 `[[email protected]/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が動作するようにします。私は何とかコピーする必要があります。

答えて

2

Fnには静的寿命があるため、namesは静的寿命よりも長くなければならないというエラーが表示されます。

  1. names'static寿命を追加します:あなたは二つの選択肢が持っている

    fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{ 
        Box::new(move|| { 
         // ... 
        }) 
    } 
    
  2. 変更names寿命に合わせて、箱入りFnの寿命:

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

閉鎖の必要性の本体namesの所有権をprinterに指定しているため、を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() 
    }) 
} 
+0

ありがとうございます!閉鎖の生涯を結びつける+は、まさに私が探していたものでした。 – somnid

関連する問題