Rust- async/await

async and await are key language features in Rust for writing asynchronous code. They were stabilized in the Rust 1.39.0 release.

Asynchronous programming is a way of writing programs that are able to do multiple things at the same time. It's particularly useful in situations where you need to handle many tasks at once, or when you have IO-bound tasks (like network requests) that often spend a lot of time waiting.

Here's how async and await work in Rust:

  • async : The async keyword in Rust is used to define an asynchronous function that returns a future. A future is a value that represents some computation that will complete in the future.

    Here is a simple async function:

    rust 复制代码
    async fn hello() {
        println!("Hello, async world!");
    }

    This hello function, when called, will produce a future. To actually execute the code inside the function, the future needs to be run on an executor.

  • await : The await keyword is used within async functions to wait for the result of a future. Unlike blocking in a traditional function, awaiting inside an async function allows other tasks to run.

    Here is an example of using await:

    rust 复制代码
    async fn hello() -> String {
        "Hello, async world!".to_string()
    }
    
    #[tokio::main] // or #[async_std::main] if you're using async-std
    async fn main() {
        let message = hello().await;
        println!("{}", message);
    }

    In this example, hello().await causes the main function to wait for the hello function to finish, and then binds its result to the message variable.

Rust's async system works on a zero-cost abstraction principle, which means there should be no additional overhead for using these features.

Note that Rust's standard library does not provide an async runtime. You'll need to use a crate like tokio or async-std to provide an executor and other tools for working with async functions and futures. These are powerful libraries that provide async versions of many standard Rust features, along with additional tools for building async applications.

rust 复制代码
use async_std::task::{sleep, spawn, block_on};
use std::{future::Future, time::Duration};

#[async_std::main]
async fn main() {
    // do3();
    // do4();

    // let do3_span = spawn(do3);
    // let do4_span = spawn(do4);

    // do3_span.join().unwrap();
    // do4_span.join().unwrap();

    // let do3_async = spawn(do3());
    // do4().await;
    // do3_async.await;

    let result = block_on(rust_study());
    println!("{}", result);     // Rust 学习目标:Programming
}

async fn lesson() -> String {
    String::from("Rust")
}

fn study1() -> impl Future<Output = String> {
    async {
        let x = lesson().await;
        x + " 学习目标:"
    }
}

fn rust_study() -> impl Future<Output = String> {
    let r = |x: String| async move {
        let y: String = study1().await;
        y + &*x
    };
    r(String::from("Programming"))
}

async fn do3() {
    for i in 1..=5 {
        println!("do3 {}", i);
        sleep(Duration::from_millis(500)).await;
    }
}

async fn do4() {
    for i in 1..=5 {
        println!("do4 {}", i);
        sleep(Duration::from_millis(1000)).await;
    }
}

// fn do3() {
//     for i in 1..=5 {
//         println!("do3 {}", i);
//         sleep(Duration::from_millis(500));
//     }
// }

// fn do4() {
//     for i in 1..=5 {
//         println!("do4 {}", i);
//         sleep(Duration::from_millis(1000));
//     }
// }
相关推荐
q平面人1 小时前
【总工笔记】mindoc平板、桌面端笔记软件,发布到mindoc服务端
rust·tauri·华为平板·mindoc·总工笔记
MC皮蛋侠客3 小时前
Tauri 2.x 系列(九):安全模型——Capabilities、Permissions、Scope 与 CSP
rust·tauri
Source.Liu4 小时前
【Dioxus】Windows 环境下 Rust + Dioxus 安装配置笔记
windows·rust·dioxus
zLLM_Lab10 小时前
不装 Python/PyTorch:8.1 MB Rust 程序在 MacBook Air M5 跑多模态大模型
rust
梦醒沉醉11 小时前
std1.97.1——result模块细览
rust
Thneonl13 小时前
同一资源、不同 ID:多源拓扑的 Identity Resolution
架构·rust
绍磊leo14 小时前
【保姆级】dora-rs 一键安装脚本:类ros2的fishros 风格交互菜单 + 国内镜像加速,把坑都替你踩完了
rust·dora-rs
Ramble_Naylor1 天前
只借不占:Rust 的引用与借用
开发语言·rust
k4m7v2pz1 天前
交叉编译 Rust 到 aarch64 Linux 掌机:glibc 版本与 sysroot 重建的完整踩坑记录
rust·glibc·交叉编译·aarch64·zigbuild·sysroot
k4m7v2pz1 天前
用 Rust 重造 Java 的 CLI 分发体验:从 java -jar 到 wasmtime run
rust·跨平台·webassembly·wasmtime·wasi·java-jar