arrays - Rust 是如何实现数组索引的?

标签 arrays rust indices mutability

我正在学习子结构类型系统,Rust 就是一个很好的例子。

数组在 Rust 中是可变的,它可以被多次访问而不是只能访问一次。 “值读取”、“引用读取”和“可变引用读取”之间有什么区别?我编写了如下程序,但出现了一些错误。

fn main() {
    let xs: [i32; 5] = [1, 2, 3, 4, 5];
    println!("first element of the array: {}", xs[1]);
    println!("first element of the array: {}", &xs[1]);
    println!("first element of the array: {}", &mut xs[1]);
}

这是错误信息:

error[E0596]: cannot borrow immutable indexed content `xs[..]` as mutable
 --> src/main.rs:5:53
  |
2 |     let xs: [i32; 5] = [1, 2, 3, 4, 5];
  |         -- consider changing this to `mut xs`
...
5 |     println!("first element of the array: {}", &mut xs[1]);
  |                                                     ^^^^^ cannot mutably borrow immutable field

最佳答案

xs可变的;为了使其可变,其绑定(bind)必须包含 mut 关键字:

let mut xs: [i32; 5] = [1, 2, 3, 4, 5];

添加它后,您的代码将按预期工作。我推荐the relevant section in The Rust Book .

Rust 中的索引是 Index 提供的操作和 IndexMut特征,并且如文档中所述,它是 *container.index(index)*container.index_mut(index) 的语法糖,这意味着它提供直接访问(不仅仅是引用)索引元素。通过 assert_eq 比较可以更好地看出您列出的 3 个操作之间的差异:

fn main() {
    let mut xs: [i32; 5] = [1, 2, 3, 4, 5];

    assert_eq!(xs[1], 2); // directly access the element at index 1
    assert_eq!(&xs[1], &2); // obtain a reference to the element at index 1
    assert_eq!(&mut xs[1], &mut 2); // obtain a mutable reference to the element at index 1

    let mut ys: [String; 2] = [String::from("abc"), String::from("def")];

    assert_eq!(ys[1], String::from("def"));
    assert_eq!(&ys[1], &"def");
    assert_eq!(&mut ys[1], &mut "def");
}

关于arrays - Rust 是如何实现数组索引的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279852/

相关文章:

c# - JToken 类型转换?

javascript - Node.js - 段错误 : 11 With Quite Large Array

encryption - 即使数据正确,AES-GCM 256 解密也会失败

javascript - 删除或忽略数组中的空单元格

javascript - 如何访问数组中对象中的数组?

rust - 如何将字符迭代器转换为字符串?

rust - 调用函数返回但未分配的值的所有权会发生什么情况?

indices - DirectX 12 索引缓冲区

OpenGL:VAO 和 VBO 是否适用于大型多边形渲染任务?

arrays - SAS中具有不同索引和缺失值的数组处理