我把一个Rust程序函数标记为async之后,当它被执行时返回一个Future对象,是这样吧? 那我持有这个对象后应该在什么时候通过什么方式得到这个async函数的实际返回值呢? 如果我没有使用Future对象,接下来又会发生什么呢?

UUUUUUUUUU
是的,您理解是正确的。让我们详细解答您的问题。

1. async 函数的行为

当你将一个 Rust 函数标记为 async 时,函数不会立即返回结果,而是返回一个 Future 对象。这个 Future 表示计算的结果,并且会在某个时刻完成(即变为 Ready 状态,包含计算结果)。

例如:

async fn example() -> i32 {
    42
}

调用 example() 会返回一个 Future<i32> 对象,而不会直接返回 42

2. 何时通过 Future 获取实际返回值

要得到 async 函数的实际返回值,你需要"驱动"这个 `Future 对象的执行。这个驱动的方式通常有以下几种:

(1) 在 异步环境 中使用 await

如果你在一个异步函数中调用 async 函数,你应该使用 .await 来等待 Future 完成并获取返回值。

例如:

async fn example() -> i32 {
    42
}

async fn main() {
    let result = example().await;  // .await 会得到 Future 的结果
    println!("{}", result);
}

在这里,example().await 会等待 example 函数的完成并返回 42

(2) 使用 tokio::runtime::Runtime 或其他运行时

如果你在一个 同步 函数(如 main)中调用 async 函数,你不能直接使用 .await,因为你不能在同步上下文中使用异步代码。在这种情况下,你可以通过 tokio::runtime::Runtime 来创建一个运行时,并使用 block_on 来执行 Future

例如:

use tokio::runtime::Runtime;

async fn example() -> i32 {
    42
}

fn main() {
    let rt = Runtime::new().unwrap();  // 创建一个 Tokio runtime
    let result = rt.block_on(example());  // block_on 会等待 Future 执行并得到结果
    println!("{}", result);
}

block_on 会阻塞当前线程,直到 Future 完成并返回结果。

3. 如果没有使用 Future 对象会发生什么?

如果你调用一个 async 函数但没有使用返回的 Future 对象,函数就不会被执行。

例如,下面的代码不会执行 example 函数:

async fn example() -> i32 {
    42
}

fn main() {
    example();  // 没有使用 .await 或 .block_on,所以不会执行
}

在这个例子中,example() 只是返回了一个 Future 对象,但没有任何东西去等待这个 Future,因此 example 函数的内容实际上不会执行。

4. 重要总结

  • 异步函数 (async fn) 返回一个 Future,而不是立即执行和返回结果。
  • 如果在异步函数内调用 async 函数,需要使用 .await 来得到结果。
  • 如果在同步函数内调用 async 函数,可以通过 block_on 来执行并等待 Future 完成。
  • 如果没有处理返回的 Future 对象,async 函数的内容不会执行。

因此,async 函数需要正确地驱动(通过 awaitblock_on)才能执行其逻辑并获取结果。

posted on   及途又八  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示