Reputation: 1
I am learning rust, Run the following code. I want to change each value of the array
use rand::Rng;
// fn main() {
// let mut x: [i32; 30] = [1; 30];
// for (index, value) in x.iter().enumerate() {
// // no worker
// x[index] = rand::thread_rng().gen_range(1..100);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `x[_]` occurs here
// println!("{}", x[index]);
// }
// }
fn main() {
let mut x = [1; 30];
let enumerate = x.iter().enumerate();
for index in 0..x.len() {
// worker!
x[index] = rand::thread_rng().gen_range(1..100);
println!("{}", x[index]);
}
}
I want to know why
Upvotes: 0
Views: 88
Reputation:
The error is happening because the code is trying to modify an array while it's being used by an iterator. To fix this, you need to use an iterator that allows you to modify the array.
In Rust, there's a distinction between iter()
and iter_mut()
. iter()
returns an iterator that gives you read-only access to the elements of an array, while iter_mut()
returns an iterator that gives you mutable access to the elements of an array.
So, in your code, instead of using x.iter().enumerate()
, you can use x.iter_mut().enumerate()
to get an iterator that lets you modify the elements of x
:
use rand::Rng;
fn main() {
let mut x: [i32; 30] = [1; 30];
for (_, value) in x.iter_mut().enumerate() {
*value = rand::thread_rng().gen_range(1..100);
println!("{}", *value);
}
}
Upvotes: 1