gpt4 book ai didi

rust - 我将如何使用特征对象进行函数回调?

转载 作者:行者123 更新时间:2023-11-29 07:52:30 45 4
gpt4 key购买 nike

我正在努力思考特征对象以及如何使用它们。一种情况是我可能想传递回调函数,当满足某些条件时调用回调。

fn bind_callback( key: u64, /* pass function */) {
// when key is matched with the event, call the function
}

我该怎么做呢?我听说我可以使用 trait 对象来做这样的事情,但我将如何实现呢?有人可以给我举个例子吗?这就是我的意思:

trait Callback {
fn callback(self);
}

fn pass_callback(f: &Callback) {
f.callback();
}

fn run_me() {
println!("Hello World!");
}

fn main() {
pass_callback(&run_me); // run simple no arg void ret function
pass_callback(|| println!("Hello World!")); // same thing
}

我知道这是非常错误的,我正在努力了解我将如何完成这样的事情。我的错误输出是:

<anon>:14:19: 14:26 error: the trait `Callback` is not implemented for the type `fn() {run_me}` [E0277]
<anon>:14 pass_callback(&run_me);
^~~~~~~
<anon>:14:19: 14:26 help: see the detailed explanation for E0277
<anon>:14:19: 14:26 note: required for the cast to the object type `Callback`
<anon>:15:19: 15:46 error: mismatched types:
expected `&Callback`,
found `[closure@<anon>:15:19: 15:46]`
(expected &-ptr,
found closure) [E0308]
<anon>:15 pass_callback(|| println!("Hello World!"));
^~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:15:19: 15:46 help: see the detailed explanation for E0308
error: aborting due to 2 previous errors
playpen: application terminated with error code 101

最佳答案

如果你想使用闭包和函数作为参数,你不能使用你自己的特征。相反,您可以使用 Fn* 系列之一:

fn pass_callback<F>(f: F)
where F: Fn()
{
f();
}

fn run_me() {
println!("Hello World!");
}

fn main() {
pass_callback(run_me);
pass_callback(|| println!("Hello World!"));
}

如果你真的想使用你自己的特征,你可以,但是你需要在某些东西上实现特征并将那个项目传递给你的函数:

trait Callback {
fn callback(&self, value: u8) -> bool;
}

struct IsEven;
impl Callback for IsEven {
fn callback(&self, value: u8) -> bool {
value % 2 == 0
}
}

fn pass_callback<C>(f: C)
where C: Callback
{
if f.callback(42) {
println!("Callback passed");
}
}

fn main() {
pass_callback(IsEven);
}

顺便说一句,你的评论

no arg void ret function

不完全正确。 Rust 没有void“类型”,它有空元组,通常称为单元类型

关于rust - 我将如何使用特征对象进行函数回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35566342/

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