首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rust Futures for String

Rust Futures for String
EN

Stack Overflow用户
提问于 2020-07-19 03:20:30
回答 1查看 471关注 0票数 0

我一直在尝试理解和使用futures (0.3版),但是我不能让它工作。据我所知,只有当类型A实现了未来的特征时,函数才能够返回A类型的未来。如果我创建了一个结构并实现了未来的特征,这是可以的,但是为什么String不工作呢?

代码语言:javascript
复制
use futures::prelude::*;

async fn future_test() -> impl Future<Output=String> {
    return "test".to_string();
}

我得到了错误:

代码语言:javascript
复制
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

代码语言:javascript
复制
async fn future_test() -> impl Future<Output=Box<String>> {
    return Box::new("test".to_string());
}

但是错误是一样的:

代码语言:javascript
复制
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本身呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-19 08:07:44

当一个函数被声明为async时,它隐式返回一个future,函数的返回类型作为它的Output类型。因此,您可以编写以下函数:

代码语言:javascript
复制
async fn future_test() -> String {
    "test".to_string()
}

或者,如果您希望显式地将返回类型指定为Future,则可以删除async关键字。如果你这样做了,你还需要构造一个返回的未来,并且你将不能在函数中使用await

代码语言:javascript
复制
fn future_test2() -> impl Future<Output=String> {
    ready("test2".to_string())
}

请注意,futures::ready构造了一个立即就绪的Future,这在本例中是合适的,因为此函数中没有实际的异步活动。

Link to Playground

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62972822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档