Creating collection from values

George Shuklin
journey to rust
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:

  1. Create an array with value of a given size. 1, 2, etc.
  2. Call into. Most collections supports From 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.

--

--

George Shuklin
journey to rust

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.