快速入门

Rust 语言原生提供了异步操作的关键字 asyncawait,但通常还需要配合第三方的 runtime,其中最有名的就是 tokio 了。

在开始了解 Rust 的所谓异步是什么样子之前,先看一下如何写一个简单的 Rust 异步程序。

以下是 main.rs

async fn hello_world() {
    hello_cat().await;
    println!("hello, world!");
}

async fn hello_cat() {
    println!("hello, kitty!");
}

#[tokio::main] 
async fn main() {
    let future = hello_world();
    println!("start");
    future.await; 
}

Cargo.toml 文件中加入一行

[dependencies]
tokio = { version = "1", features = ["full"] }

运行上面的代码,会看到这样的输出

start
hello, kitty!
hello, world!

可以看出,future = hello_world(); 是创建一个异步执行的代码块, 并把它赋值给了 future 变量,这个代码块不会立刻执行,而是等到用户调用 await 的时候再去执行。

另:在 main 函数加上 #[tokio::main] 的目的是初始化 tokio

参考资料

  1. https://course.rs/tokio/getting-startted.html
  2. https://kaisery.github.io/trpl-zh-cn/title-page.html