2

Rust 1.64.0发布:异步是亮点

 1 year ago
source link: https://www.jdon.com/62582
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rust 1.64.0发布:异步是亮点


每六周发布一次新版本,在每个新版本中,这里都有一个包含一些亮点:

1、Rust 现在有一个与异步相关的新特性:IntoFuture。
.await 语法可用于任何实现 IntoFuture 的东西。
(类似于使用 for 循环,您可以遍历实现 IntoIterator 的任何内容。)
这允许类型提供更简单的异步接口:

std::future::{ready, IntoFuture, Ready};
struct Example;
impl IntoFuture for Example {
    type Output = 1.32;
    type IntoFuture = Ready<i32>;
    fn into_future(self) -> Ready<i32> {
     ready(123)
    }
}
async fn example( ) {
    prtntln!("Hello, {}!", Example.await);
}

2、今天的Rust版本还附带了另外两个与异步相关的工具。
std::future::poll_fn函数允许你轻松地从一个闭包中创建一个future(就像iter::from_fn用于迭代器)。
std::task::ready! () 宏会提取Poll::Ready中值,或者提前返回Pending。

let f = future::poll_fn(|cx| {
 ...
  let value = ready!(another_future.poll(ex));
  Poll::Ready(value + 1)

});

3、Rust 的 NonZero 类型获得了用于(无符号)加法、乘法、求幂、绝对数和二次幂计算的新方法,它们都保持“非零性”:它们返回 NonZero 类型,因为我们知道结果永远不会为零。

 fn  calc(x: NonZeroI32) -> NonZeroll32 {
    // Can't result  in zero, because x is never zero.
    x.unsigned_abs().saturating_add(123)
}

有关 Rust 1.64 中更完整的更改列表,点击标题。
 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK