better_comprehension
Collection comprehension and Iterator comprehension in Rust. And it provides a better experience in Rust.
Usage
The syntax is derived from [Python's comprehension] (https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).
This library provides macros for all collection types in the Rust standard library and an Iterator based on references.
simple example
let vec_1 = vec!;
let vec: = vector!;
assert_eq!;
You can also use patterns in it
let people = ;
let vec_deque = vec_deque!;
assert_eq!;
filtering values before comprehension
let linked_list = linked_list!;
assert_eq!;
return different values based on conditions
let b_tree_set = b_tree_set!;
assert_eq!;
nested comprehension
let binary_heap = binary_heap!;
assert_eq!;
the reading order of the for loop in this library is from top to bottom, just like Python's comprehension.
let vec = vector!;
assert_eq!;
Note that in Rust, for loops consume ownership. So typically, for nested loops, if you want the original container to be consumed, you should write it like this:
let vec_1 = vec!;
let vec_2 = vec!;
let vec_3 = vec!;
let vec = ;
// println!("{:?}", vec_1); // borrow of moved value
println!; // work well
// println!("{:?}", vec_3); // borrow of moved value
But in this library, you don't need to do this,
the provided macros will automatically handle these problems for you.
You only need to add .iter() or use & before the variable you want to keep ownership,
the rest will be automatically handled in the macro.
let vec_1 = vec!;
let vec_2 = vec!;
let vec_3 = vec!;
let vec = vector!;
// println!("{:?}", vec_1); // borrow of moved value
println!; // work well
// println!("{:?}", vec_3); // borrow of moved value
This library also supports key-value collection types, HashMap, BTreeMap
let vec_key = vec!;
let vec_value = ;
let hash_map = hash_map!;
assert_eq!;
Iterator comprehension is also supported, but unlike the collection comprehension above,
this iterator comprehension is based on references, so it will not consume ownership.
let vec_1 = ;
let vec_2 = ;
let mut result3 = iterator_ref!;
// still alive even there is no & or .iter()
println!;
println!;
for _ in 0..=9
/*
Some(("123", "ABC"))
Some(("123", "DEF"))
Some(("123", "GHI"))
Some(("123", "ABC"))
Some(("123", "DEF"))
Some(("123", "GHI"))
Some(("789", "DEF"))
Some(("789", "DEF"))
None
None
*/
The above writing is equivalent to the following writing
let vec_1 = ;
let vec_2 = ;
let mut result3 = ;
some details
vector! : push() to add elements
vec_deque! : push_back() to add elements
linked_list! : push_back() to add elements
binary_heap! : push() to add elements
hash_set! : insert() to add elements
b_tree_set! : insert() to add elements
hash_map! : insert() to add key-value pairs
b_tree_map! : insert() to add key-value pairs