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


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

You can use:

use std::iter;


.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).


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


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.