[英]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.