Rust- async/await

本文介绍了Rust语言中用于异步编程的关键特性async和await。async定义了返回future的异步函数,而await则在异步函数内部用来等待future的结果,允许其他任务执行。Rust的异步系统基于零开销抽象原则,使用这些特性不会带来额外的性能负担。文章还提到了需要像tokio或async-std这样的库来提供执行器和其他异步功能工具。
摘要由CSDN通过智能技术生成

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:

    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:

    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.

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));
//     }
// }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青衫客36

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值