【发布时间】:2018-06-25 01:54:13
【问题描述】:
我正在学习子结构类型系统,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
【问题讨论】:
-
我不认为
Arrays 默认是可变的;因此你的错误。 -
如果你熟悉 C++...
value reads映射到return-by-value语义,reference reads映射到 const-correctreturn-by-reference语义,而mutable reference reads在大多数情况,只是指return-by-reference语义。
标签: arrays rust indices mutability