get_id
をパラメータとする関数agg
を作成し、get_id
関数を使用するFnMut
クロージャを返します。クロージャ内で関数ポインタパラメータを使用するルチル
具体例:
エラーが発生しstruct CowRow {
pub id : i32,
}
impl CowRow {
fn get_id(&self) -> i32 { self.id }
}
pub fn agg<F>(col: F) -> Box<FnMut(&CowRow) -> i32>
where F: Fn(&CowRow) -> i32 {
let mut res = 0;
Box::new(move |r| { res += col(&r); return res })
}
fn main() {
let mut cow = CowRow { id: 0 };
let a = agg(CowRow::get_id);
a(&cow);
:
the parameter type `F` may not live long enough [E0310]
run `rustc --explain E0310` to see a detailed explanation
consider adding an explicit lifetime bound `F: 'static`...
...so that the type `[[email protected]:23:14: 23:53 col:F, res:i32]` will meet its required lifetime bounds
ここでの考え方は、私が構造体の異なるフィールド上で動作クロージャを作成することができ、一般的な機能をしたいということです。だから、私の考えは構造体のゲッターである関数を渡し、クロージャーでこれを使って適切なフィールドを抽出することでした。
私はagg
署名に'static
を加えるの様々な組み合わせを試してみたが、私はそれが実際に何を意味するのかわからないんだけど、どこでそれが構文的に移動する必要があります。さらに、私は、メソッドを特性として追加するなど、多くのテクニックを試しましたが、それを得ることはできませんでした。
完璧、ありがとう! – josh