0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VecをHashSetに変換する

Posted at

VecからHashSetを作成したい場合、まずcollectを利用する方法があります。メソッドチェーンで書ける、型推論が活用できるという点で個人的にはこちらが好みです。

let v = vec![1, 2, 2, 3, 3, 3];
let s = v.into_iter().collect::<HashSet<_>>();

もしくは、HashSet::from_iterを利用する方法もあります。ただし型推論がうまくいかずに、型の明示が必要になる場合があります。

let v: Vec<i32> = vec![1, 2, 2, 3, 3, 3];
let s: HashSet<i32> = HashSet::from_iter(v.iter().cloned());

環境情報

  • rustc 1.76.0 (07dca489a 2024-02-04)
  • cargo 1.76.0 (c84b36747 2024-01-18)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?