Is there something similar to `vec!` for other collections?


#1

Yes, I know that Vec<_> is the go-to type that should be used 99% of the cases.

However, in the small thing I am building right now, I’d really like the O(1) push and pops on both sides of the collection, so I want to use a VecDeque<_> instead.

However, in my tests and quite probably later in the code I’d want to instantiate VecDeques with multiple elements right away.

For Vec<_>, you’d do that with the vec![elem1, elem2, elem3] macro. Is there something similar for the other collections in the standard library?
Many of the examples either instantiate them empty and push_back(elem) a few times, or alternatively do this:

let mydeque : VecDeque<_> = vec![1, 2, 3, 4].into_iter().collect();

Both approaches feel more like a mitigation than a solution.

Is there an alternative?


#2

I don’t think such a macro exists in the stdlib, but it’s a short enough macro that you could define it yourself. If it turns out to be useful, publish it as a crate!


#3

Such a crate already exists!

https://crates.io/crates/collect-mac


#4

There’s also maplit for hash/btree maps/sets.