pub struct HashSet<T, S = RandomState> { /* private fields */ }
Expand description
A hash set implemented as a HashMap
where the value is ()
.
As with the HashMap
type, a HashSet
requires that the elements
implement the Eq
and Hash
traits. This can frequently be achieved by
using #[derive(PartialEq, Eq, Hash)]
. If you implement these yourself,
it is important that the following property holds:
k1 == k2 -> hash(k1) == hash(k2)
In other words, if two keys are equal, their hashes must be equal. Violating this property is a logic error.
It is also a logic error for a key to be modified in such a way that the key’s
hash, as determined by the Hash
trait, or its equality, as determined by
the Eq
trait, changes while it is in the map. This is normally only
possible through Cell
, RefCell
, global state, I/O, or unsafe code.
The behavior resulting from either logic error is not specified, but will
be encapsulated to the HashSet
that observed the logic error and not
result in undefined behavior. This could include panics, incorrect results,
aborts, memory leaks, and non-termination.
§Examples
use std::collections::HashSet;
// Type inference lets us omit an explicit type signature (which
// would be `HashSet<String>` in this example).
let mut books = HashSet::new();
// Add some books.
books.insert("A Dance With Dragons".to_string());
books.insert("To Kill a Mockingbird".to_string());
books.insert("The Odyssey".to_string());
books.insert("The Great Gatsby".to_string());
// Check for a specific one.
if !books.contains("The Winds of Winter") {
println!("We have {} books, but The Winds of Winter ain't one.",
books.len());
}
// Remove a book.
books.remove("The Odyssey");
// Iterate over everything.
for book in &books {
println!("{book}");
}
The easiest way to use HashSet
with a custom type is to derive
Eq
and Hash
. We must also derive PartialEq
,
which is required if Eq
is derived.
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq, Debug)]
struct Viking {
name: String,
power: usize,
}
let mut vikings = HashSet::new();
vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
// Use derived implementation to print the vikings.
for x in &vikings {
println!("{x:?}");
}
A HashSet
with a known list of items can be initialized from an array:
§Usage in const
and static
Like HashMap
, HashSet
is randomly seeded: each HashSet
instance uses a different seed,
which means that HashSet::new
cannot be used in const context. To construct a HashSet
in the
initializer of a const
or static
item, you will have to use a different hasher that does not
involve a random seed, as demonstrated in the following example. A HashSet
constructed this
way is not resistant against HashDoS!
use std::collections::HashSet;
use std::hash::{BuildHasherDefault, DefaultHasher};
use std::sync::Mutex;
const EMPTY_SET: HashSet<String, BuildHasherDefault<DefaultHasher>> =
HashSet::with_hasher(BuildHasherDefault::new());
static SET: Mutex<HashSet<String, BuildHasherDefault<DefaultHasher>>> =
Mutex::new(HashSet::with_hasher(BuildHasherDefault::new()));
Implementations§
Source§impl<T> HashSet<T, RandomState>
impl<T> HashSet<T, RandomState>
1.0.0 · Sourcepub fn new() -> HashSet<T, RandomState>
pub fn new() -> HashSet<T, RandomState>
Creates an empty HashSet
.
The hash set is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
§Examples
1.0.0 · Sourcepub fn with_capacity(capacity: usize) -> HashSet<T, RandomState>
pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState>
Creates an empty HashSet
with at least the specified capacity.
The hash set will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the hash set will not allocate.
§Examples
Source§impl<T, S> HashSet<T, S>
impl<T, S> HashSet<T, S>
1.0.0 · Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the set can hold without reallocating.
§Examples
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
pub fn iter(&self) -> Iter<'_, T> ⓘ
An iterator visiting all elements in arbitrary order.
The iterator element type is &'a T
.
§Examples
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert("a");
set.insert("b");
// Will print in an arbitrary order.
for x in set.iter() {
println!("{x}");
}
§Performance
In the current implementation, iterating over set takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.6.0 · Sourcepub fn drain(&mut self) -> Drain<'_, T> ⓘ
pub fn drain(&mut self) -> Drain<'_, T> ⓘ
Clears the set, returning all elements as an iterator. Keeps the allocated memory for reuse.
If the returned iterator is dropped before being fully consumed, it drops the remaining elements. The returned iterator keeps a mutable borrow on the set to optimize its implementation.
§Examples
Sourcepub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, T, F> ⓘ
🔬This is a nightly-only experimental API. (hash_extract_if
#59618)
pub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, T, F> ⓘ
hash_extract_if
#59618)Creates an iterator which uses a closure to determine if a value should be removed.
If the closure returns true, then the value is removed and yielded. If the closure returns false, the value will remain in the list and will not be yielded by the iterator.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain
with a negated predicate if you do not need the returned iterator.
§Examples
Splitting a set into even and odd values, reusing the original set:
#![feature(hash_extract_if)]
use std::collections::HashSet;
let mut set: HashSet<i32> = (0..8).collect();
let extracted: HashSet<i32> = set.extract_if(|v| v % 2 == 0).collect();
let mut evens = extracted.into_iter().collect::<Vec<_>>();
let mut odds = set.into_iter().collect::<Vec<_>>();
evens.sort();
odds.sort();
assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
1.18.0 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns false
.
The elements are visited in unsorted (and unspecified) order.
§Examples
use std::collections::HashSet;
let mut set = HashSet::from([1, 2, 3, 4, 5, 6]);
set.retain(|&k| k % 2 == 0);
assert_eq!(set, HashSet::from([2, 4, 6]));
§Performance
In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.7.0 (const: 1.85.0) · Sourcepub const fn with_hasher(hasher: S) -> HashSet<T, S>
pub const fn with_hasher(hasher: S) -> HashSet<T, S>
Creates a new empty hash set which will use the given hasher to hash keys.
The hash set is also created with the default initial capacity.
Warning: hasher
is normally randomly generated, and
is designed to allow HashSet
s to be resistant to attacks that
cause many collisions and very poor performance. Setting it
manually using this function can expose a DoS attack vector.
The hash_builder
passed should implement the BuildHasher
trait for
the HashMap to be useful, see its documentation for details.
§Examples
1.7.0 · Sourcepub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S>
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S>
Creates an empty HashSet
with at least the specified capacity, using
hasher
to hash the keys.
The hash set will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the hash set will not allocate.
Warning: hasher
is normally randomly generated, and
is designed to allow HashSet
s to be resistant to attacks that
cause many collisions and very poor performance. Setting it
manually using this function can expose a DoS attack vector.
The hash_builder
passed should implement the BuildHasher
trait for
the HashMap to be useful, see its documentation for details.
§Examples
1.9.0 · Sourcepub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the set’s BuildHasher
.
§Examples
Source§impl<T, S> HashSet<T, S>
impl<T, S> HashSet<T, S>
1.0.0 · Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the HashSet
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
§Panics
Panics if the new allocation size overflows usize
.
§Examples
1.57.0 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the HashSet
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling try_reserve
,
capacity will be greater than or equal to self.len() + additional
if
it returns Ok(())
.
Does nothing if capacity is already sufficient.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
1.0.0 · Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the set as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
§Examples
1.56.0 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
pub fn shrink_to(&mut self, min_capacity: usize)
Shrinks the capacity of the set with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
If the current capacity is less than the lower limit, this is a no-op.
§Examples
1.0.0 · Sourcepub fn difference<'a>(
&'a self,
other: &'a HashSet<T, S>,
) -> Difference<'a, T, S> ⓘ
pub fn difference<'a>( &'a self, other: &'a HashSet<T, S>, ) -> Difference<'a, T, S> ⓘ
Visits the values representing the difference,
i.e., the values that are in self
but not in other
.
§Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// Can be seen as `a - b`.
for x in a.difference(&b) {
println!("{x}"); // Print 1
}
let diff: HashSet<_> = a.difference(&b).collect();
assert_eq!(diff, [1].iter().collect());
// Note that difference is not symmetric,
// and `b - a` means something else:
let diff: HashSet<_> = b.difference(&a).collect();
assert_eq!(diff, [4].iter().collect());
1.0.0 · Sourcepub fn symmetric_difference<'a>(
&'a self,
other: &'a HashSet<T, S>,
) -> SymmetricDifference<'a, T, S> ⓘ
pub fn symmetric_difference<'a>( &'a self, other: &'a HashSet<T, S>, ) -> SymmetricDifference<'a, T, S> ⓘ
Visits the values representing the symmetric difference,
i.e., the values that are in self
or in other
but not in both.
§Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// Print 1, 4 in arbitrary order.
for x in a.symmetric_difference(&b) {
println!("{x}");
}
let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
assert_eq!(diff1, diff2);
assert_eq!(diff1, [1, 4].iter().collect());
1.0.0 · Sourcepub fn intersection<'a>(
&'a self,
other: &'a HashSet<T, S>,
) -> Intersection<'a, T, S> ⓘ
pub fn intersection<'a>( &'a self, other: &'a HashSet<T, S>, ) -> Intersection<'a, T, S> ⓘ
Visits the values representing the intersection,
i.e., the values that are both in self
and other
.
When an equal element is present in self
and other
then the resulting Intersection
may yield references to
one or the other. This can be relevant if T
contains fields which
are not compared by its Eq
implementation, and may hold different
value between the two equal copies of T
in the two sets.
§Examples
1.0.0 · Sourcepub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> ⓘ
pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> ⓘ
Visits the values representing the union,
i.e., all the values in self
or other
, without duplicates.
§Examples
1.0.0 · Sourcepub fn contains<Q>(&self, value: &Q) -> bool
pub fn contains<Q>(&self, value: &Q) -> bool
1.9.0 · Sourcepub fn get<Q>(&self, value: &Q) -> Option<&T>
pub fn get<Q>(&self, value: &Q) -> Option<&T>
Sourcepub fn get_or_insert(&mut self, value: T) -> &T
🔬This is a nightly-only experimental API. (hash_set_entry
#60896)
pub fn get_or_insert(&mut self, value: T) -> &T
hash_set_entry
#60896)Inserts the given value
into the set if it is not present, then
returns a reference to the value in the set.
§Examples
Sourcepub fn get_or_insert_with<Q, F>(&mut self, value: &Q, f: F) -> &T
🔬This is a nightly-only experimental API. (hash_set_entry
#60896)
pub fn get_or_insert_with<Q, F>(&mut self, value: &Q, f: F) -> &T
hash_set_entry
#60896)Inserts a value computed from f
into the set if the given value
is
not present, then returns a reference to the value in the set.
§Examples
#![feature(hash_set_entry)]
use std::collections::HashSet;
let mut set: HashSet<String> = ["cat", "dog", "horse"]
.iter().map(|&pet| pet.to_owned()).collect();
assert_eq!(set.len(), 3);
for &pet in &["cat", "dog", "fish"] {
let value = set.get_or_insert_with(pet, str::to_owned);
assert_eq!(value, pet);
}
assert_eq!(set.len(), 4); // a new "fish" was inserted
Sourcepub fn entry(&mut self, value: T) -> Entry<'_, T, S>
🔬This is a nightly-only experimental API. (hash_set_entry
#60896)
pub fn entry(&mut self, value: T) -> Entry<'_, T, S>
hash_set_entry
#60896)Gets the given value’s corresponding entry in the set for in-place manipulation.
§Examples
#![feature(hash_set_entry)]
use std::collections::HashSet;
use std::collections::hash_set::Entry::*;
let mut singles = HashSet::new();
let mut dupes = HashSet::new();
for ch in "a short treatise on fungi".chars() {
if let Vacant(dupe_entry) = dupes.entry(ch) {
// We haven't already seen a duplicate, so
// check if we've at least seen it once.
match singles.entry(ch) {
Vacant(single_entry) => {
// We found a new character for the first time.
single_entry.insert()
}
Occupied(single_entry) => {
// We've already seen this once, "move" it to dupes.
single_entry.remove();
dupe_entry.insert();
}
}
}
}
assert!(!singles.contains(&'t') && dupes.contains(&'t'));
assert!(singles.contains(&'u') && !dupes.contains(&'u'));
assert!(!singles.contains(&'v') && !dupes.contains(&'v'));
1.0.0 · Sourcepub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool
pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool
Returns true
if self
has no elements in common with other
.
This is equivalent to checking for an empty intersection.
§Examples
1.0.0 · Sourcepub fn is_subset(&self, other: &HashSet<T, S>) -> bool
pub fn is_subset(&self, other: &HashSet<T, S>) -> bool
Returns true
if the set is a subset of another,
i.e., other
contains at least all the values in self
.
§Examples
1.0.0 · Sourcepub fn is_superset(&self, other: &HashSet<T, S>) -> bool
pub fn is_superset(&self, other: &HashSet<T, S>) -> bool
Returns true
if the set is a superset of another,
i.e., self
contains at least all the values in other
.
§Examples
1.0.0 · Sourcepub fn insert(&mut self, value: T) -> bool
pub fn insert(&mut self, value: T) -> bool
Adds a value to the set.
Returns whether the value was newly inserted. That is:
- If the set did not previously contain this value,
true
is returned. - If the set already contained this value,
false
is returned, and the set is not modified: original value is not replaced, and the value passed as argument is dropped.
§Examples
1.9.0 · Sourcepub fn replace(&mut self, value: T) -> Option<T>
pub fn replace(&mut self, value: T) -> Option<T>
Adds a value to the set, replacing the existing value, if any, that is equal to the given one. Returns the replaced value.
§Examples
1.0.0 · Sourcepub fn remove<Q>(&mut self, value: &Q) -> bool
pub fn remove<Q>(&mut self, value: &Q) -> bool
Trait Implementations§
1.0.0 · Source§impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1.0.0 · Source§impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1.0.0 · Source§impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1.4.0 · Source§impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1.0.0 · Source§impl<T, S> Extend<T> for HashSet<T, S>
impl<T, S> Extend<T> for HashSet<T, S>
Source§fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
Source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one
#72631)1.0.0 · Source§impl<T, S> FromIterator<T> for HashSet<T, S>
impl<T, S> FromIterator<T> for HashSet<T, S>
1.0.0 · Source§impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
1.0.0 · Source§impl<T, S> IntoIterator for HashSet<T, S>
impl<T, S> IntoIterator for HashSet<T, S>
Source§fn into_iter(self) -> IntoIter<T> ⓘ
fn into_iter(self) -> IntoIter<T> ⓘ
Creates a consuming iterator, that is, one that moves each value out of the set in arbitrary order. The set cannot be used after calling this.
§Examples
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert("a".to_string());
set.insert("b".to_string());
// Not possible to collect to a Vec<String> with a regular `.iter()`.
let v: Vec<String> = set.into_iter().collect();
// Will print in an arbitrary order.
for x in &v {
println!("{x}");
}