collection_macro
This crate provides the general-purpose seq![] and map! {} macros.
[]
= "0.1"
We also show off how to bypass the Orphan Rule to create incredibly versatile macros.
Usage
These macros rely on type inference to determine the collection that they create.
The real power of these macros lies in the fact that work with absolutely any collection type, even collections from other crates.
seq![]
Takes a list of expressions, and creates a sequence like Vec<T> or HashSet<T>:
let seq: = seq!;
You can use the array syntax seq![expr; amount]:
let seq: = seq!;
assert_eq!;
You can create non-empty sequences, like ones from the mitsein crate:
extern crate mitsein;
use ;
use NonEmpty;
;
// we usually can't implement external trait `Seq1Plus`
// for external struct `NonEmpty`,
// but because `BypassOrphanRule` is a local type, and it is
// inferred in the `seq!` macro, this works!
// it just works!!
let seq: = seq!;
assert_eq!;
Non-empty sequences fail to compile if no arguments are provided:
let seq: = seq!;
Traits:
- If your type implements
Seq0<T>, then it can be used withseq![]syntax - If your type implements
Seq1Plus<T>, then it can be used with 1+ argument to:seq![1, 2] - If your type implements both
Seq0<T>andSeq1Plus<T>then you can use the array syntax:seq![0; 10]
seq! can be used with these standard library types by default:
But you can use it with any struct, even the ones from external crates by implementing the traits Seq0 and Seq1Plus.
Tips:
- For a sequence of 0 or more elements can such as
Vec<T>, implement bothSeq0andSeq1Plus - If your sequence is non-empty like
NonEmpty<Vec<T>>, implement justSeq1Plus- thenseq![]will be a compile error
map! {}
Takes a list of key => value pairs, and creates a map like HashMap<K, V> or BTreeMap<K, V>:
let seq: = map! ;
assert_eq!;
Traits:
- If your type implements
Map0<K, V>, then it can be used withmap! {}syntax - If your type implements
Map1Plus<K, V>, then it can be used with 1+ argument to:map! { 'A' => 0x41, 'b' => 0x62 }
map! can be used with these standard library types by default:
But you can use it with any struct, even the ones from external crates by implementing the traits [Map0] and [Map1Plus].
Tips:
- For a map of 0 or more
key => valuepairs can such asHashMap<K, V>, implement both [Map0] and [Map1Plus] - If your map is non-empty like
NonEmpty<HashMap<K, V>>, implement just [Map1Plus] - thenmap! {}will be a compile error