繁体   English   中英

Rust 字符串期货

[英]Rust Futures for String

我一直在尝试理解和使用futures (0.3 版),但无法完成这项工作。 据我了解,只有当A类型实现了未来特征时,function 才能返回 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本身?

当 function 被声明为async时,它隐式返回一个未来,返回类型 function 作为其Output类型。 所以你会写这个 function:

async fn future_test() -> String {
    "test".to_string()
}

或者,如果您想将返回类型显式指定为Future ,您将删除async关键字。 如果你这样做了,你还需要构造一个返回的未来,你将无法在 function 中使用await

fn future_test2() -> impl Future<Output=String> {
    ready("test2".to_string())
}

请注意, futures::ready构造了一个立即就绪的 Future,这在这种情况下是合适的,因为在这个 function 中没有实际的异步活动。

链接到游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM