【问题标题】:Is there a way to create a function pointer to a method in Rust?有没有办法在 Rust 中创建一个指向方法的函数指针?
【发布时间】:2019-06-03 23:04:16
【问题描述】:

例如,

struct Foo;

impl Foo {
    fn bar(&self) {}
    fn baz(&self) {}
}

fn main() {
    let foo = Foo;
    let callback = foo.bar;
}
error[E0615]: attempted to take value of method `bar` on type `Foo`
  --> src/main.rs:10:24
   |
10 |     let callback = foo.bar;
   |                        ^^^ help: use parentheses to call the method: `bar()`

【问题讨论】:

    标签: rust


    【解决方案1】:

    使用fully-qualified syntaxFoo::bar 将起作用,产生fn(&Foo) -> ()(类似于 Python)。

    let callback = Foo::bar;
    // called like
    callback(&foo);
    

    但是,如果您希望它与已绑定的 self 变量一起使用(例如,调用 callback() 将与在 foo 对象上调用 bar 相同),那么您需要使用显式闭包:

    let callback = || foo.bar();
    // called like
    callback();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2011-02-12
      • 2014-07-21
      • 2022-01-21
      相关资源
      最近更新 更多