Build HashSet from a vector in Rust

后端 未结 3 1205
谎友^
谎友^ 2021-02-06 21:03

I want to build a HashSet from a Vec. I\'d like to do this

  1. in one line of code,
  2. copying the data only once,<
3条回答
  •  轮回少年
    2021-02-06 21:58

    The following should work nicely; it fulfills your requirements:

    use std::collections::HashSet;
    use std::iter::FromIterator;
    
    fn vec_to_set(vec: Vec) -> HashSet {
        HashSet::from_iter(vec)
    }
    

    from_iter() works on types implementing IntoIterator, so a Vec argument is sufficient.

    Additional remarks:

    • you don't need to explicitly return function results; you only need to omit the semi-colon in the last expression in its body

    • I'm not sure which version of Rust you are using, but on current stable (1.12) to_iter() doesn't exist

提交回复
热议问题