如何通过函数中的可变引用重新分配数组

时间:2019-11-07 06:56:37

标签: rust

我是Rust的新手,在引用和所有权的概念上遇到了麻烦。我只想重新分配一个数组,但是遇到了错误。我尝试了以下方法:

fn change(a: &mut [i64; 3]) {
    a = [5, 4, 1];
}

但出现以下错误:

 --> 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]`

我尝试将&mut添加到数组中,但是出现了一个全新的错误。有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:5)

变量a是对数组的可变引用。如果您写a = ...;,则表示您尝试更改引用本身(即,之后a引用另一个数组)。但这不是您想要的。您想要更改参考后面的原始值。为此,您必须使用* 取消引用:

*a = [5, 4, 1];

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];
  |     ^^

它已经告诉您解决方案!使用Rust时,阅读完整的错误消息确实值得:)