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));
//     }
// }
相关推荐
爱吃牛肉的大老虎2 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
TunerT_TQ5 小时前
Valhalla 静态工程审阅 #008|RisingWave 源码证据驱动评测【大厂开源基础设施特辑】
rust·开源·github·实时数据处理·流式数据库·apacheflink·streamingsql
TunerT_TQ9 小时前
Valhalla 静态工程审阅 #007|AgentENV 源码证据驱动评测【大厂开源基础设施特辑】
rust·开源·go·github·sandbox·分布式系统·ai基础设施
爱吃牛肉的大老虎9 小时前
Rust基础之函数和错误
java·开发语言·rust
NutShell Wang10 小时前
Vite 8.1 深度拆解:Rolldown 统一打包器如何终结前端构建的「双引擎时代」
前端·rust·开源·vite·开发者工具·vibe coding
寒水馨11 小时前
macOS下载、安装uv-0.12.0(附安装包uv-aarch64-apple-darwin.tar.gz)
python·macos·rust·项目管理·包管理器·astral·pip替代
寒水馨12 小时前
macOS下载、安装ripgrep-15.2.0(附安装包ripgrep-15.2.0-aarch64-apple-darwin.tar.gz)
macos·正则表达式·rust·ripgrep·rg·命令行搜索·代码搜索
SomeB1oody1 天前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程
骊城英雄1 天前
Rust从入门到精通-trait
人工智能·算法·rust
花褪残红青杏小1 天前
Rust图像处理第23节-图像加噪:给每个像素单独掷一次骰子
rust·webassembly·图形学