【Rust日报】 2019-10-27 为什么async函数很难写?
- 2019 年 10 月 31 日
- 笔记
用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