to_vec()in rust

2023-04-18

to_vec is a crate that provides specialized implementations of collect for common use cases when collecting into Vec, HashSet, or HashMap containers. The main functionality can be broken down into:

  • ToVec: Collects an iterator's items into a Vec. For example:

    #![allow(unused)]
    fn main() {
    use to_vec::ToVec;
    let v = "one two three".split_whitespace().to_vec();
    assert_eq!(v, &["one", "two", "three"]);
    }

    Source 0

  • ToVecResult: Collects an iterator of Result<T, E> into a Result<Vec<T>, E>, where the error is the first error encountered.

    #![allow(unused)]
    fn main() {
    use to_vec::ToVecResult;
    let numbers = "23E 5F5 FF00".split_whitespace()
        .map(|s| u32::from_str_radix(s, 16)).to_vec_result().unwrap();
    assert_eq!(numbers, &[0x23E, 0x5F5, 0xFF00]);
    }

    Source 0

Some other similar crates

  • ToSet: Collects an iterator of references into a HashSet, implicitly cloning the items.

    #![allow(unused)]
    fn main() {
    use to_vec::ToSet;
    let colours = ["green", "orange", "blue"].iter().to_set();
    let fruit = ["apple", "banana", "orange"].iter().to_set();
    let common = colours.intersection(&fruit).to_set();
    assert_eq!(common, ["orange"].iter().to_set());
    }

    Source 0

  • ToMap: Collects an iterator of references to key-value pairs into a HashMap, implicitly cloning the keys and values.

    #![allow(unused)]
    fn main() {
    use to_vec::ToMap;
    const VALUES: &[(&str, i32)] = &[("hello", 10), ("dolly", 20)];
    let map = VALUES.iter().to_map();
    assert_eq!(map.get("hello"), Some(&10));
    assert_eq!(map.get("dolly"), Some(&20));
    }

    Source 0

These specialized forms provide a more ergonomic and efficient way to collect iterators into commonly used containers.

Warning

This is done with the help of phined