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

3

我刚接触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个回答

9

变量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时,阅读完整的错误消息真的很值得 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接