Build HashSet from a vector in Rust

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

    Moving data ownership

    let vec: Vec = vec![1, 2, 3, 4];
    let hash_set: HashSet = vec.into_iter().collect();
    

    Cloning data

    let vec: Vec = vec![1, 2, 3, 4];
    let hash_set: HashSet = vec.iter().cloned().collect();
    

提交回复
热议问题