Creating collection from values
Published in
Nov 3, 2022
I believe I just found a very idiomatic way to create a single-elemented collection (like HashSet, Vec, VecDeque, etc).
… actually, not a single-elemented. Any fixed number of elements.
Just look at this:
[value].into()
What it does:
- Create an array with value of a given size. 1, 2, etc.
- Call
into
. Most collections supportsFrom
for array.
This is full example:
let a: std::collections::HashSet<_> = [true].into();
let b: std::vec::Vec<_> = ['a', 'b'].into();
Alternative I know is to use .iter().collect()
which is more buttons to push and more convoluted.