Rust异步编程基础
学习async/await语法和异步运行时 · 难度:入门 · +15XP
异步编程简介
异步编程允许程序在等待I/O操作时执行其他任务,提高并发性能。Rust使用async/await语法,配合运行时(如tokio)实现高效异步。async函数返回Future trait,由执行器驱动。
基本语法
use tokio::time::{sleep, Duration};
async fn do_something() -> String {
sleep(Duration::from_secs(1)).await;
String::from("完成")
}
#[tokio::main]
async fn main() {
let result = do_something().await;
println!("{}", result);
}
并发执行
使用tokio::join!同时运行多个异步任务:
async fn task1() -> u32 { 10 }
async fn task2() -> u32 { 20 }
#[tokio::main]
async fn main() {
let (a, b) = tokio::join!(task1(), task2());
println!("结果: {} + {} = {}", a, b, a + b);
}
异步运行时
| 运行时 | 特点 |
|---|---|
| tokio | 最流行,功能丰富 |
| async-std | 类似std API |
| smol | 轻量级 |
错误处理
异步函数可以返回Result:
async fn fetch_data() -> Result<String, String> {
Ok(String::from("数据"))
}
#[tokio::main]
async fn main() {
match fetch_data().await {
Ok(data) => println!("成功: {}", data),
Err(e) => eprintln!("错误: {}", e),
}
}
练习提示
编写一个程序,同时发起多个HTTP请求并汇总结果。使用tokio::spawn创建任务。