从Rust中的向量构建HashSet [英] Build HashSet from a vector in Rust

查看:153
本文介绍了从Rust中的向量构建HashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Vec<u8>构建一个HashSet<u8>.我想这样做

I want to build a HashSet<u8> from a Vec<u8>. I'd like to do this

  1. 在一行代码中,
  2. 仅复制一次数据,
  3. 仅使用2n内存
  1. in one line of code,
  2. copying the data only once,
  3. using only 2n memory,

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

but the only thing I can get to compile is this piece of .. junk, which I think copies the data twice and uses 3n memory.

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

我希望写一些简单的东西,像这样:

I was hoping to write something simple, like this:

fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
    return HashSet::from_iter(vec.iter());
}

但是不会编译:

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, _>`

..而且我不太理解错误消息,可能是因为我需要进行RTFM.

.. and I don't really understand the error message, probably because I need to RTFM.

推荐答案

由于该操作不需要使用向量¹,因此我认为它不应使用它.这只会导致程序中其他地方的额外复制:

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<u8> {
    HashSet::from_iter(data.iter().cloned())
}

hashset(&v)这样称呼,其中vVec<u8>或其他强制切成切片的事物.

Call it like hashset(&v) where v is a Vec<u8> 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.

¹这是基于元素类型u8Copy的,即它不具有所有权语义.

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

这篇关于从Rust中的向量构建HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆