[英]How does Rust implement array indexing?
我正在學習子結構類型系統,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
是不可變的; 為了使其可變,其綁定必須包含mut
關鍵字:
let mut xs: [i32; 5] = [1, 2, 3, 4, 5];
當您添加它時,您的代碼將按預期工作。 我建議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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.