[英]How do I pass an array to a function in Rust and change its content?
我想将数组传递给函数并更改其中的内容:
fn change_value(mut arr: &[i32]) {
arr[1] = 10;
}
fn main() {
let mut arr: [i32; 4] = [1, 2, 3, 4];
change_value(&arr);
println!("this is {}", arr[1]);
}
我收到此错误:
warning: variable does not need to be mutable
--> src/main.rs:2:17
|
2 | fn change_value(mut arr: &[i32]) {
| ----^^^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default
error[E0594]: cannot assign to `arr[_]` which is behind a `&` reference
--> src/main.rs:3:5
|
2 | fn change_value(mut arr: &[i32]) {
| ------ help: consider changing this to be a mutable reference: `&mut [i32]`
3 | arr[1] = 10;
| ^^^^^^^^^^^ `arr` is a `&` reference, so the data it refers to cannot be written
warning: variable does not need to be mutable
--> src/main.rs:7:9
|
7 | let mut arr: [i32; 4] = [1, 2, 3, 4];
| ----^^^
| |
| help: remove this `mut`
我一直在四处寻找,但找不到任何东西。
Rust 引用(由&
符号表示)有两种:不可变( &T
)和可变( &mut T
)。 为了改变引用后面的值,这个引用必须是可变的,所以你需要:
&mut [i32]
作为函数参数,而不是&[i32]
&mut arr
传递给函数,而不是&arr
: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]);
}
您不需要mut arr
在change_value
的参数中,因为mut
表示该变量的可变性,而不是它指向的数据的可变性。 使用mut arr: &[i32]
您可以重新分配arr
本身(使其指向不同的切片),但您不能更改它引用的数据。
如果你想接受一个数组而不是一个slice ,你也可以这样做:
fn change_value(arr: &mut [i32; 4]) {
arr[1] = 10;
}
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.