Velcro - collection initialization macros

velcro.

Originally, this was just a simple declarative macro to help reduce the size of some of our tests that combine lists of messages to set up some initial state. The first version could initialize vectors, with the ability to use .. to spread arguments that implement IntoIterator:

use velcro::vec;
let my_vec = vec![1, 2, ..(3..10)];
let my_other_vec = vec![1, 2, ..my_vec, 100];

But I wanted it to perform the same as std::vec! when the input was compatible (ie when .. is not used), and to support the different types of input that std::vec! supports, which would justify using the same name as the built-in macro. This was really only practical with a proc macro and led to adding other collection types, including maps, e.g.:

use velcro::hash_map;
let my_map = hash_map! {
    '*': 0,
    ..('a'..='z'): 1,
    ..('A'..='Z'): 2,
}

There are also *_from variations for each macro, that perform an Into::into() on each element. This turns out to be particularly convenient for initializing maps that have String keys because it means you can use char and &str literals:

use velcro::hash_map_from;
let my_map: HashMap<String, u32> = hash_map_from! {
    '*': 0,
    ..('a'..='z'): 1,
    ..('A'..='Z'): 2,
    "foo": 10,
}

Feedback and contributions welcome!

5 Likes

This looks really useful! Thanks :slight_smile:

Glad you like it!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.