LoginSignup
2
0

More than 3 years have passed since last update.

Rustで構造体に関数を返却させるメソッド追加するの

Posted at

構造体に関数を返却させるメソッド追加するの、
対象メソッドのself引数に「&'static」ライフタイムを追加して、
newメソッドをconstにするとできた。

// 構造体のフィールドに持たせた値を使用した関数を作成したい。
type ResultFn = Box<dyn Fn(i32) -> i32 + 'static>;

fn main() {
    static P:Pom = Pom::new(&8);
    let add_fn = P.make_add_fn();
    assert_eq!(15, add_fn(7));
    println!("function result:{}", add_fn(10));
}

struct Pom{p:&'static i32}

impl Pom{

    pub const fn new(q:&'static i32) -> Pom{
        Pom{p:q}
    }

    fn make_add_fn(&'static self)->ResultFn {
        Box::new(move |r| self.p + r)
    }
}

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0