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.
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.
You can use:
use std::iter;
vec.extend(iter::repeat(n).take(len));
.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).
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.