相关疑难解决方法(0)

从Rust中的向量构建HashSet

我想建立一个HashSet<u8>来自Vec<u8>.我想这样做

  1. 在一行代码中,
  2. 仅复制一次数据,
  3. 仅使用2n记忆,

但我唯一可以编译的就是这段...垃圾,我认为这两次复制数据并使用3n内存.

fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
    let mut victim = vec.clone();
    let x: HashSet<u8> = victim.drain(..).collect();
    return x;
}
Run Code Online (Sandbox Code Playgroud)

我希望写一些简单的东西,比如:

fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
    return HashSet::from_iter(vec.iter());
}
Run Code Online (Sandbox Code Playgroud)

但那不会编译:

error[E0308]: mismatched types
 --> <anon>:5:12
  |
5 |     return HashSet::from_iter(vec.iter());
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found &u8
  |
  = note: expected type `std::collections::HashSet<u8>`
  = note:    found type `std::collections::HashSet<&u8, _>`
Run Code Online (Sandbox Code Playgroud)

..我真的不明白错误信息,可能是因为我需要RTFM.

vector hashset rust

25
推荐指数
3
解决办法
7183
查看次数

标签 统计

hashset ×1

rust ×1

vector ×1