asynchronous - 字符串的 Rust 期货
问题描述
我一直在尝试理解和使用futures
(0.3 版),但无法完成这项工作。A
据我了解,只有当类型A
实现未来特征时,函数才能返回类型的未来。如果我创建一个结构并实现未来的特征,那没关系,但为什么String
不起作用?
use futures::prelude::*;
async fn future_test() -> impl Future<Output=String> {
return "test".to_string();
}
我得到错误:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
所以我告诉自己,好吧,我可以Box
像这样使用:
async fn future_test() -> impl Future<Output=Box<String>> {
return Box::new("test".to_string());
}
但错误是一样的:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
我究竟做错了什么?为什么未来持有的是String
而不是Box
它本身?
解决方案
当一个函数被声明async
时,它隐式地返回一个未来,函数的返回类型作为它的Output
类型。所以你会写这个函数:
async fn future_test() -> String {
"test".to_string()
}
或者,如果您想将返回类型显式指定为 a Future
,则可以删除async
关键字。如果你这样做了,你还需要构造一个返回的未来,你将无法await
在函数内部使用。
fn future_test2() -> impl Future<Output=String> {
ready("test2".to_string())
}
请注意,它futures::ready
构造了一个立即就绪的 Future,这在这种情况下是合适的,因为此函数中没有实际的异步活动。
推荐阅读
- python-3.x - 右键单击Windows中执行python脚本的文件夹后如何选择菜单选项?
- java - 在 Java 8 中将方法作为参数传递?
- python - 如何在表格中添加滑动条?
- r - R中的t分布
- flutter - 按下后退按钮时如何在后台发送应用程序
- php - fsockopen():SSL:在codeigniter电子邮件发送中由对等方重置连接
- excel - 尝试从 1 个选项卡复制并粘贴到新选项卡时出现 VBA 错误
- android - 有没有办法使用 Kotlin Anko Alertdialog 来处理屏幕旋转变化?
- python - 我无法在 selenium 中使用 python 请求会话 cookie
- mysql - 如何在 Laravel 中加入 2 个表?