有没有办法在 Rust 中创建指向方法的函数指针? [英] Is there a way to create a function pointer to a method in Rust?

查看:18
本文介绍了有没有办法在 Rust 中创建指向方法的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

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()`

推荐答案

With 完全限定语法Foo::bar 将起作用,产生一个fn(&Foo) ->()(类似于Python).

With fully-qualified syntax, Foo::bar will work, yielding a fn(&Foo) -> () (similar to Python).

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

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

However, if you want it with the self variable already bound (as in, calling callback() will be the same as calling bar on the foo object), then you need to use an explicit closure:

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

这篇关于有没有办法在 Rust 中创建指向方法的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆