1

In Rust, we can create a Vector with macro vec![].

let numbers = vec![1, 2, 3];

Is there any similar macro that allow us to create a HashSet?

From the doc https://doc.rust-lang.org/std/collections/struct.HashSet.html, I notice that we have HashSet::from:

let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]);

However, that requires us to create an array first, which seems a bit wasteful.

Yuchen
  • 30,852
  • 26
  • 164
  • 234
  • https://lib.rs/crates/map-macro – PitaJ Dec 03 '22 at 04:39
  • There is no cost for creating a array, since in rust objects are created on the stack by default, so there will be no allocation. Especially if the array is static. Vectors are different though, they need dynamic space. – mousetail Dec 03 '22 at 07:57

2 Answers2

3

The standard library doesn't have a macro for this. This crate does provide one though.

As for the wastefulness, creating an array of string literals is pretty cheap, and is almost certainly optimized away.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
  • 1
    Creating an array of a few thousand `&'static str` was not optimized away when I tried (with rustc 1.61). I think the optimizer just gave up. – Caesar Dec 03 '22 at 11:27
1

If you fear the overhead of constructing the HashSet at runtime, or want this to be a static, the phf crates might help you.

Caesar
  • 6,733
  • 4
  • 38
  • 44