gpt4 book ai didi

rust - 有没有办法在 Rust 中创建指向方法的函数指针?

转载 作者:行者123 更新时间:2023-11-29 07:42:37 25 4
gpt4 key购买 nike

例如,

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

最佳答案

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

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

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

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

关于rust - 有没有办法在 Rust 中创建指向方法的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com