Flavius
Flavius

Reputation: 13826

Mutate an array through a slice of the array

let mut a = [1, 2, 3, 4, 5];
let mut window = &a[1..4];
for element in window.iter() {
    println!("{}", element);
    *element = 0;
}

How to set the middle values in the original array a to 0 through the slice window?

Upvotes: 1

Views: 1931

Answers (1)

Levans
Levans

Reputation: 15012

In your precise case, if you don't try to make overlapping slices, you can simply create a &mut slice:

let mut a = [1, 2, 3, 4, 5];
let window = &mut a[1..4];
for element in window.iter_mut() {
    println!("{}", element);
    *element = 0;
}

Upvotes: 4

Related Questions