[solved] Fill a vector or a slice with a value


#1

Is there an equivalent of vec![n; len] that fills an existing vector with a given value? (i.e. sets every element to n)

I thought I’ve seen something like vec.fill(n), but it doesn’t exist.


[Solved] How to fill a Vec with a value
#2

You can use:

use std::iter;
vec.extend(iter::repeat(n).take(len));

#3

.resize() if you want to add them as new elements, and a for loop if you want to overwrite. (Yes resize ends up using the same code path as the vec![] macro for adding elements).


#4

https://doc.rust-lang.org/std/ptr/fn.write_bytes.html :slight_smile:


#5

slice.fill(x) was proposed in drafts of RFC 1419 but didn’t make the final cut because of open questions about what trade-offs it should make between performance guarantees versus flexibility.