簡體   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