当前位置 : 主页 > 编程语言 > java >

【Rust日报】 2019-10-27 為什麼async函數很難寫?

来源:互联网 收集:自由互联 发布时间:2022-06-30
用commit範例教你使用async與std::future::Future Read more rustorm 0.15 目前可以使用 sqlite, postgres, mysql Read more 為什麼async函數很難寫? 他想異步地對數據庫執行各種操作 如果使用了 async_trait 這個

用commit範例教你使用async與std::future::Future

Read more

rustorm 0.15

目前可以使用 sqlite, postgres, mysql 

Read more

為什麼async函數很難寫?

他想異步地對數據庫執行各種操作

如果使用了 async_trait 這個庫

#[async_trait]
trait Database {
async fn get_user(&self) -> User;
}

等同於

trait Database {
fn get_user(&self) -> Pin<Box<dyn Future<Output = User> + Send + '_>>;
}

這會有一些問題

  • 回傳 ​​impl Trait​​ in traits 是不支援的
  • 變成 ​​impl Trait​​ in traits 要 GATs generic associated type

    他這邊要實作就要用

    trait Database {
    type GetUser<'s>: Future<Output = User> + 's;
    fn get_user(&self) -> Self::GetUser<'_>;
    }

    用生命週期的原因是異步fn總是捕獲所有參數

    因此我們返回的任何類型都將&self作為回傳的一部分,因此它必須包含生命週期。

  • send bounds限制
  • 如果您要編寫通用代碼,則可能需要將生成的結果指定為Send。

    像這樣

    fn finagle_database<D: Database>(d: &D)
    where
    for<'s> D::GetUser<'s>: Send,
    {
    ...
    spawn(d.get_user());
    ...
    }
  • 異步函數要有 dyn trait
  • 要避免問題 #1 跟 #2, async-trait 讓 async fn返回dyn Future而不是impl Future。

    要避免問題 #3, async-trait 你可以選用 Pin<Box<dyn Future + Send>> (您選擇用“Send”)。 這幾乎是最常用的默認值。

    這個問題解法非常複雜,小編我難以完全理解,請有興趣的人可以去看看。

    Read more

    圖形化介紹各種好用的cmd工具

    Read more

    const fn 中使用 if 跟 match

    即將進 nightly 版本

    Read more

    zstd 壓縮演算法實作

    Zstandard是由Facebook的Yann Collet開發的一個無失真資料壓縮演算法。該名稱也指其C語言的參考實現。第1版的實現於2016年8月31日

    Read more

    已序陣列 插入/移除 時間複雜度 O(√N)

    實作1 實作2 論文


    日报订阅地址:

    独立日报订阅地址:

    • Telgram Channel
    • 阿里云语雀订阅
    • Steemit
    • GitHub

    社区学习交流平台订阅:

    • Rust.cc论坛: 支持rss
    • Rust Force: 支持rss
    • 微信公众号:Rust语言学习交流


    上一篇:AWS 赞助 Rust 中文社区创业者
    下一篇:没有了
    网友评论