What is the idiomatic way to assign one value to a slice in Rust?

Viewed 83

I would like to assign a value to a slice a[start..end] (suppose a: &mut Vec<usize>), and of course a traditional for can meet this requirement:

for i in start..end {
    a[i] = value;
}

I also tried a[start..end].copy_from_slice(&vec![value; end - start]), but clearly it is much slower.

I would like to know whether there is an idiomatic way to do so in Rust.

2 Answers

Starting with 1.50, you can use slice::fill on a subslice:

a[start..end].fill(value);

You can use the iterator trait to modify it:

a[start..end].iter_mut().for_each(|v| *v = value);

Playground

Related