如何将数组传递给Rust中的函数并更改其内容?

时间:2020-12-23 20:00:36

I want to pass an array to a function and change the content inside it. How can I do that, this is my code below, but of course it doesn't work.

我想将一个数组传递给一个函数并更改其中的内容。我该怎么做呢,这是我下面的代码,但当然不行。

fn change_value(mut arr: &[int]) {
    arr[1] = 10;
}

fn main() {
    let mut arr: [int, ..4] = [1, 2, 3, 4];
    change_value(arr);
    println!("this is {}", arr[1]);
}

I'm getting the error: "cannot assign to immutable vec content arr[..]".

我得到了错误:“不能分配到不可变的vec内容arr[.]”。

I've been searching around, but as a pretty novice Rust programmer, I can't find anything. Also it doesn't help that Rust changes its language quite a lot so a lot of methods of doing this are deprecated or removed.

我一直在四处寻找,但作为一个新手,我找不到任何东西。而且,铁锈改变了它的语言也没有多大帮助,所以很多这样做的方法都被弃用或删除了。

1 个解决方案

#1


29  

Rust references (denoted by & sign) are of two kinds: immutable (&T) and mutable (&mut T). In order to change the value behind the reference, this reference has to be mutable, so you just need to pass &mut [i32] to the function, not &[i32]:

铁锈引用(用&符号表示)有两种:不可变(&T)和可变(&mut T)。

fn change_value(arr: &mut [i32]) {
    arr[1] = 10;
}

fn main() {
    let mut arr: [i32; 4] = [1, 2, 3, 4];
    change_value(&mut arr);
    println!("this is {}", arr[1]);
}

You also don't need mut arr in change_value argument because mut there denotes mutability of that variable, not of the data it points to. So, with mut arr: &[int] you can reassign arr itself (for it to point to a different slice), but you can't change the data it references.

在change_value参数中也不需要mut arr,因为mut表示该变量的可变性,而不是它指向的数据。因此,通过mut arr: &[int],您可以重新分配arr本身(以便它指向另一个片),但是您不能更改它引用的数据。

#1


29  

Rust references (denoted by & sign) are of two kinds: immutable (&T) and mutable (&mut T). In order to change the value behind the reference, this reference has to be mutable, so you just need to pass &mut [i32] to the function, not &[i32]:

铁锈引用(用&符号表示)有两种:不可变(&T)和可变(&mut T)。

fn change_value(arr: &mut [i32]) {
    arr[1] = 10;
}

fn main() {
    let mut arr: [i32; 4] = [1, 2, 3, 4];
    change_value(&mut arr);
    println!("this is {}", arr[1]);
}

You also don't need mut arr in change_value argument because mut there denotes mutability of that variable, not of the data it points to. So, with mut arr: &[int] you can reassign arr itself (for it to point to a different slice), but you can't change the data it references.

在change_value参数中也不需要mut arr,因为mut表示该变量的可变性,而不是它指向的数据。因此,通过mut arr: &[int],您可以重新分配arr本身(以便它指向另一个片),但是您不能更改它引用的数据。