首页    新闻    小组    威客    人才    下载    博客    代码贴    在线编程    论坛
Rust 1.50.0 稳定版发布,改进数组索引
2021年2月14日 16:09 | 阅读 2066 次

Rust 1.50.0 稳定版已发布,此版本改进了数组索引、扩展了对联合字段 (union field) 的安全访问,并将其添加到标准库。

具备 const-generic 特性的数组索引

此版本为任意长度const N的数组[T; N]增加了ops::IndexIndexMut实现,索引操作符[]可通过内置的 compiler magic 在数组中运行。


fn second<C>(container: &C) -> &C::Output
where
    C: std::ops::Index<usize> + ?Sized,
{
    &container[1]
}

fn main() {
    let array: [i32; 3] = [1, 2, 3];
    assert_eq!(second(&array[..]), &2); // slices worked before
    assert_eq!(second(&array), &2); // now it also works directly
}

数组中定义为const类型的值支持重复

Rust 的数组可以写为列表[a, b, c]或重复形式[x; N]


fn main() {
    // This is not allowed, because `Option<Vec<i32>>` does not implement `Copy`.
    let array: [Option<Vec<i32>>; 10] = [None; 10];

    const NONE: Option<Vec<i32>> = None;
    const EMPTY: Option<Vec<i32>> = Some(Vec::new());

    // However, repeating a `const` value is allowed!
    let nones = [NONE; 10];
    let empties = [EMPTY; 10];
}

针对ManuallyDrop<T>联合字段的安全分配

Rust 1.49 支持将ManuallyDrop<T>字段添加到union,从而允许合并Drop。不过,当一个字段被赋值时,union不会丢弃旧的值,因为它们不知道哪个变体此前是有效的,所以安全的 Rust 以前只限制为仅限于Copy类型,而Copy类型从来不会Drop。当然,ManuallyDrop<T>也不需要Drop,因此 Rust 1.50 现在允许对这些字段进行安全分配。

Rust 1.50.0 还新增了 9 个稳定的函数:

  • bool::then
  • btree_map::Entry::or_insert_with_key
  • f32::clamp
  • f64::clamp
  • hash_map::Entry::or_insert_with_key
  • Ord::clamp
  • RefCell::take
  • slice::fill
  • UnsafeCell::get_mut

详细更新说明点此查看。

延伸阅读

  • Rust 基金会成立,创始成员包括华为、Microsoft、Google
  • 微软组建 Rust 开发人员团队
  • httpd 使用 Rust 重写 mod_ssl 模块

(文/开源中国)    




评论 (0)
游客请输入验证码
最新评论
0
0
收藏