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));
//     }
// }
相关推荐
五月君_6 小时前
Bun v1.3.14 发布,Rust 版即将进 Claude Code 内测,下一版可能就告别 Zig
开发语言·后端·rust
techdashen11 小时前
深入 Rust enum 的内存世界
开发语言·后端·rust
techdashen13 小时前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust
Arman_15 小时前
02 rusty-cat 实战:MeowClient 配置、任务参数、进度回调与暂停恢复
http·https·rust·tokio·文件分片上传·文件分片下载
wzhao10115 小时前
Relink 0.15.1:一个 no_std 的 ELF 加载器/链接器
linux·rust·gnu
yzwlord17 小时前
【无标题】
linux·运维·rust·ssh
Arman_17 小时前
Rust 客户端安全上传下载阿里云 OSS:rusty-cat 预签名 URL 实战
安全·阿里云·rust·oss断点续传
灵机一物18 小时前
灵机一物AI原生电商小程序、PC端(已上线)-【技术深度解析】Bun 6 天 AI 重写 96 万行代码:从 Zig 迁移 Rust 全流程与行业影响
开发语言·人工智能·rust
Arman_18 小时前
03 rusty-cat 进阶解析:架构设计、云存储接入、安全模型与长期维护评估
css·安全·rust·文件分片上传·文件分片下载
techdashen18 小时前
半小时读懂 Rust:从语法符号到所有权思维
开发语言·rust