我是Rust的新手,在引用和所有权的概念上遇到了麻烦。我只想重新分配一个数组,但是遇到了错误。我尝试了以下方法:
fn change(a: &mut [i64; 3]) {
a = [5, 4, 1];
}
Run Code Online (Sandbox Code Playgroud)
但出现以下错误:
--> main.rs:6:7
|
6 | a = [5, 4, 1];
| ^^^^^^^^^
| |
| expected mutable reference, found array of 3 elements
| help: consider mutably borrowing here: `&mut [5, 4, 1]`
|
= note: expected type `&mut [i64; 3]`
Run Code Online (Sandbox Code Playgroud)
我尝试将添加&mut到数组中,但是出现了一个全新的错误。有人可以指出我正确的方向吗?
该变量a是对数组的可变引用。如果您编写a = ...;,则尝试更改引用本身(即,之后a引用另一个数组)。但这不是您想要的。您想要更改参考后面的原始值。为此,您必须使用以下方式取消引用*:
*a = [5, 4, 1];
Run Code Online (Sandbox Code Playgroud)
Rust 1.38及更高版本的错误消息甚至更好:
error[E0308]: mismatched types
--> src/lib.rs:2:9
|
2 | a = [5, 4, 1];
| ^^^^^^^^^ expected mutable reference, found array of 3 elements
|
= note: expected type `&mut [i64; 3]`
found type `[{integer}; 3]`
help: consider dereferencing here to assign to the mutable borrowed piece of memory
|
2 | *a = [5, 4, 1];
| ^^
Run Code Online (Sandbox Code Playgroud)
它已经告诉您解决方案!使用Rust时,阅读完整的错误消息确实值得:)