gpt4 book ai didi

rust - 简单的 future 示例

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

我正在尝试做一个简单的 future 示例。我关注了https://blog.logrocket.com/a-practical-guide-to-async-in-rust/
所以我做了:

use futures::Future;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

pub async fn receive_fut(
f: &mut dyn FnMut(&[u8])
) -> impl Future<Output = Result<Vec<u8>>> {
futures::future::ok(Ok(Vec::new())).await
}
但是我明白了
error[E0277]: `std::result::Result<std::result::Result<Vec<_>, _>, _>` is not a future
--> src/lib.rs:6:10
|
6 | ) -> impl Future<Output = Result<Vec<u8>>> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `std::result::Result<std::result::Result<Vec<_>, _>, _>` is not a future
|
= help: the trait `futures::Future` is not implemented for `std::result::Result<std::result::Result<Vec<_>, _>, _>`

error: aborting due to previous error
如果我使用 futures::future::ok将它转换为将来的结果,为什么std::result::Result应该实现将来的?

最佳答案

这在文章中得到了回答:

Async functions differ in one important way: all your return types are “wrapped” into a Future.

You might read the documentation about Futures in Rust and think your async function needs to look like this:

async fn our_async_program() -> impl Future<Output = Result<String>> {
future::ok("Hello world".to_string()).await
}

This is wrong! If you’re doing this, you’re overthinking it. An async function already wraps the return type, so you can write functions the way you’re used to.

This is what you actually want:

async fn our_async_program() -> Result<String> {
future::ok("Hello world".to_string()).await
}

因此,您需要删除返回类型的 impl Future<...部分:
pub async fn receive_fut(
f: &mut dyn FnMut(&[u8])
) -> Result<Vec<u8>> {
futures::future::ok(Ok(Vec::new())).await
}
然后意识到 future::ok 已经产生了 Result::Ok,因此您无需再次将其包装在 Ok()中。
pub async fn receive_fut(
f: &mut dyn FnMut(&[u8])
) -> Result<Vec<u8>> {
futures::future::ok(Vec::new()).await
}

关于rust - 简单的 future 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574341/

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