Rust 1.45.0 发布

Rust 1.45.0 已发布。此版本有两个值得关注的变化:一是修复将大浮点数转换为小整数时出现的 undefined behavior 问题,官方将这种情况称为 unsoundness;二是在 expression, patterns 和 statement 中使用函数式过程宏(procedural macros)的功能已处于稳定阶段。

修复浮点数转换为整数时的 unsoundness

对于此问题,官方的解决方案是为as关键字执行"saturating cast"。下面的例子解释了什么叫 saturating cast。

fn cast(x: f32) -> u8 {
    x as u8
}

fn main() {
    let too_big = 300.0;
    let too_small = -100.0;
    let nan = f32::NAN;

    println!("too_big_casted = {}", cast(too_big));
    println!("too_small_casted = {}", cast(too_small));
    println!("not_a_number_casted = {}", cast(nan));
}

上面的代码打印出

too_big_casted = 255
too_small_casted = 0
not_a_number_casted = 0

或者使用采用 unsafe 方式的新 API 进行转换:

let x: f32 = 1.0;
let y: u8 = unsafe { x.to_int_unchecked() };

稳定在 expression, patterns 和 statement 中使用函数式过程宏的功能

Rust 1.45.0 在三个新地方增加了调用过程宏的功能:

// imagine we have a procedural macro named "mac"

mac!(); // item position, this was what was stable before

// but these three are new:
fn main() {
  let expr = mac!(); // expression position

  match expr {
      mac!() => {} // pattern position
  }

  mac!(); // statement position
}

库变更

在 Rust 1.45.0 中,以下 API 已处于稳定阶段:

此外还增加了char with ranges 来迭代代码点(codepoint):

for ch in 'a'..='z' {
    print!("{}", ch);
}
println!();
// Prints "abcdefghijklmnopqrstuvwxyz"

详情查看 https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html

相关链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值