gpt4 book ai didi

asynchronous - 如何在回调中使用Rust future ?

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

有什么方法可以在回调中使用 future 吗?例如...

// Send message on multiple channels while removing ones that are closed.

use smol::channel::Sender;

...

// (expecting bool, found opaque type)
vec_of_sender.retain( |sender| async {
sender.send(msg.clone()).await.is_ok()
});

我的解决方法是循环两次:在第一遍中,我删除关闭的发件人(非异步),在第二遍中,我进行实际的发送(使用 for sender in ...异步)。但是似乎我应该可以在一个 retain()调用中完成所有操作。

最佳答案

您不能以这种方式使用retainretain接受的闭包必须实现FnMut(&T) -> bool,但是每个async函数都返回Future的实现。
您可以通过阻止异步功能将其转变为同步功能。例如,如果您使用的是tokio,则可以执行以下操作:

use tokio::runtime::Runtime;

let rt = Runtime::new().unwrap();

vec_of_sender.retain(|sender| {
rt.block_on(async { sender.send().await.is_ok() })
});
但是,添加异步运行时会产生开销,并且我感觉到您正在尝试解决错误的问题。

关于asynchronous - 如何在回调中使用Rust future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65241788/

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