Rust如何实现数组索引?

Cod*_*bit 0 arrays mutability indices rust

我正在学习子结构类型系统,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]);
}
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

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]);
}
Run Code Online (Sandbox Code Playgroud)

lje*_*drz 5

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

let mut xs: [i32; 5] = [1, 2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)

当您添加它时,您的代码将按预期工作。我建议The Rust Book中的相关部分

Rust中的索引是由IndexIndexMuttraits 提供的操作,如文档所述,它是*container.index(index)and 的语法糖*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");
}
Run Code Online (Sandbox Code Playgroud)