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

1 Like

You can use:

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

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

3 Likes

write_bytes in std::ptr - Rust :slight_smile:

1 Like

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.

Update: slice::fill was added in Rust 1.50.

2 Likes