Build HashSet from a vector in Rust

后端 未结 3 1216
谎友^
谎友^ 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:51

    Because the operation does not need to consume the vector¹, I think it should not consume it. That only leads to extra copying somewhere else in the program:

    use std::collections::HashSet;
    use std::iter::FromIterator;
    
    fn hashset(data: &[u8]) -> HashSet {
        HashSet::from_iter(data.iter().cloned())
    }
    

    Call it like hashset(&v) where v is a Vec or other thing that coerces to a slice.

    There are of course more ways to write this, to be generic and all that, but this answer sticks to just introducing the thing I wanted to focus on.

    ¹This is based on that the element type u8 is Copy, i.e. it does not have ownership semantics.

提交回复
热议问题