[英]Call async code from sync impl of trait in Rust
我正在開發我的第一個玩具項目,它包含一個簡單的 API 和 Rocket 框架。 但我被一個非常基本的需求所困,我很想就如何解決這個問題向您提供見解。
對於某些端點,我需要調用外部 REST API,所以我使用reqwest
crate 來這樣做。 我更喜歡異步執行,因為我希望我的 API 在該端點上有很多並發請求。
另一方面,我使用簡潔/六邊形架構指南來實現整個想法,然后我使用特征作為一種接口。 這有助於測試和 mocking 等。
它看起來如何:
pub trait DataFetcher {
fn fetch_data(path: String) -> Result<String, Box<dyn sts::error::Error>>,
}
pub struct DataProvider {
}
impl DataProvider {
pub fn new() -> Self {
// constructor here.
}
}
impl DataFetcher for DataProvider {
pub fetch_data(path: String) -> Result<String, Box<dyn std::error::Error>> {
// call to external REST API should be here.
}
}
問題來了:async trait methods are not supported in Rust 2018。這是我的猜測:
你有什么建議? 你有一些我可以從中得到啟發的示例項目嗎?
async-trait
crate 絕對不是實驗性的。 它是使用最廣泛的 crate 之一,並且是 traits 中異步 fns 的標准解決方案。
但是,如果您不需要抽象,我不會使用特征。 這只會使代碼復雜化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.