Struct HashSet
struct HashSet<T, S = crate::hash::RandomState, A: Allocator = crate::alloc::Global> { ... }
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 HashSet;
// Type inference lets us omit an explicit type signature (which
// would be `HashSet<String>` in this example).
let mut books = new;
// Add some books.
books.insert;
books.insert;
books.insert;
books.insert;
// Check for a specific one.
if !books.contains
// Remove a book.
books.remove;
// Iterate over everything.
for book in &books
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 HashSet;
let mut vikings = new;
vikings.insert;
vikings.insert;
vikings.insert;
vikings.insert;
// Use derived implementation to print the vikings.
for x in &vikings
A HashSet with a known list of items can be initialized from an array:
use HashSet;
let viking_names = from;
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 HashSet;
use ;
use Mutex;
const EMPTY_SET: =
with_hasher;
static SET: =
new;
Implementations
impl<T> HashSet<T, RandomState>
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
use HashSet; let set: = new;fn with_capacity(capacity: usize) -> HashSet<T, RandomState>Creates an empty
HashSetwith at least the specified capacity.The hash set will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the hash set will not allocate.Examples
use HashSet; let set: = with_capacity; assert!;
impl<T, A: Allocator> HashSet<T, RandomState, A>
fn new_in(alloc: A) -> HashSet<T, RandomState, A>Creates an empty
HashSetin the provided allocator.The hash set is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
fn with_capacity_in(capacity: usize, alloc: A) -> HashSet<T, RandomState, A>Creates an empty
HashSetwith at least the specified capacity.The hash set will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the hash set will not allocate.Examples
use HashSet; let set: = with_capacity; assert!;
impl<T, S> HashSet<T, S>
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:
hasheris normally randomly generated, and is designed to allowHashSets 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_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use RandomState; let s = new; let mut set = with_hasher; set.insert;fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S>Creates an empty
HashSetwith at least the specified capacity, usinghasherto hash the keys.The hash set will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the hash set will not allocate.Warning:
hasheris normally randomly generated, and is designed to allowHashSets 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_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use RandomState; let s = new; let mut set = with_capacity_and_hasher; set.insert;
impl<T, S, A> HashSet<T, S, A>
fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore elements to be inserted in theHashSet. The collection may reserve more space to speculatively avoid frequent reallocations. After callingreserve, capacity will be greater than or equal toself.len() + additional. Does nothing if capacity is already sufficient.Panics
Panics if the new allocation size overflows
usize.Examples
use HashSet; let mut set: = new; set.reserve; assert!;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalmore elements to be inserted in theHashSet. The collection may reserve more space to speculatively avoid frequent reallocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use HashSet; let mut set: = new; set.try_reserve.expect;fn shrink_to_fit(self: &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
use HashSet; let mut set = with_capacity; set.insert; set.insert; assert!; set.shrink_to_fit; assert!;fn shrink_to(self: &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
use HashSet; let mut set = with_capacity; set.insert; set.insert; assert!; set.shrink_to; assert!; set.shrink_to; assert!;fn difference<'a>(self: &'a Self, other: &'a HashSet<T, S, A>) -> Difference<'a, T, S, A>Visits the values representing the difference, i.e., the values that are in
selfbut not inother.Examples
use HashSet; let a = from; let b = from; // Can be seen as `a - b`. for x in a.difference let diff: = a.difference.collect; assert_eq!; // Note that difference is not symmetric, // and `b - a` means something else: let diff: = b.difference.collect; assert_eq!;fn symmetric_difference<'a>(self: &'a Self, other: &'a HashSet<T, S, A>) -> SymmetricDifference<'a, T, S, A>Visits the values representing the symmetric difference, i.e., the values that are in
selfor inotherbut not in both.Examples
use HashSet; let a = from; let b = from; // Print 1, 4 in arbitrary order. for x in a.symmetric_difference let diff1: = a.symmetric_difference.collect; let diff2: = b.symmetric_difference.collect; assert_eq!; assert_eq!;fn intersection<'a>(self: &'a Self, other: &'a HashSet<T, S, A>) -> Intersection<'a, T, S, A>Visits the values representing the intersection, i.e., the values that are both in
selfandother.When an equal element is present in
selfandotherthen the resultingIntersectionmay yield references to one or the other. This can be relevant ifTcontains fields which are not compared by itsEqimplementation, and may hold different value between the two equal copies ofTin the two sets.Examples
use HashSet; let a = from; let b = from; // Print 2, 3 in arbitrary order. for x in a.intersection let intersection: = a.intersection.collect; assert_eq!;fn union<'a>(self: &'a Self, other: &'a HashSet<T, S, A>) -> Union<'a, T, S, A>Visits the values representing the union, i.e., all the values in
selforother, without duplicates.Examples
use HashSet; let a = from; let b = from; // Print 1, 2, 3, 4 in arbitrary order. for x in a.union let union: = a.union.collect; assert_eq!;fn contains<Q>(self: &Self, value: &Q) -> bool where T: Borrow<Q>, Q: Hash + Eq + ?SizedReturns
trueif the set contains a value.The value may be any borrowed form of the set's value type, but
HashandEqon the borrowed form must match those for the value type.Examples
use HashSet; let set = from; assert_eq!; assert_eq!;fn get<Q>(self: &Self, value: &Q) -> Option<&T> where T: Borrow<Q>, Q: Hash + Eq + ?SizedReturns a reference to the value in the set, if any, that is equal to the given value.
The value may be any borrowed form of the set's value type, but
HashandEqon the borrowed form must match those for the value type.Examples
use HashSet; let set = from; assert_eq!; assert_eq!;fn get_or_insert(self: &mut Self, value: T) -> &TInserts the given
valueinto the set if it is not present, then returns a reference to the value in the set.Examples
use HashSet; let mut set = from; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // 100 was insertedfn get_or_insert_with<Q, F>(self: &mut Self, value: &Q, f: F) -> &T where T: Borrow<Q>, Q: Hash + Eq + ?Sized, F: FnOnce(&Q) -> TInserts a value computed from
finto the set if the givenvalueis not present, then returns a reference to the value in the set.Examples
use HashSet; let mut set: = .iter.map.collect; assert_eq!; for &pet in & assert_eq!; // a new "fish" was insertedfn entry(self: &mut Self, value: T) -> Entry<'_, T, S, A>Gets the given value's corresponding entry in the set for in-place manipulation.
Examples
use HashSet; use *; let mut singles = new; let mut dupes = new; for ch in "a short treatise on fungi".chars assert!; assert!; assert!;fn is_disjoint(self: &Self, other: &HashSet<T, S, A>) -> boolReturns
trueifselfhas no elements in common withother. This is equivalent to checking for an empty intersection.Examples
use HashSet; let a = from; let mut b = new; assert_eq!; b.insert; assert_eq!; b.insert; assert_eq!;fn is_subset(self: &Self, other: &HashSet<T, S, A>) -> boolReturns
trueif the set is a subset of another, i.e.,othercontains at least all the values inself.Examples
use HashSet; let sup = from; let mut set = new; assert_eq!; set.insert; assert_eq!; set.insert; assert_eq!;fn is_superset(self: &Self, other: &HashSet<T, S, A>) -> boolReturns
trueif the set is a superset of another, i.e.,selfcontains at least all the values inother.Examples
use HashSet; let sub = from; let mut set = new; assert_eq!; set.insert; set.insert; assert_eq!; set.insert; assert_eq!;fn insert(self: &mut Self, value: T) -> boolAdds a value to the set.
Returns whether the value was newly inserted. That is:
- If the set did not previously contain this value,
trueis returned. - If the set already contained this value,
falseis returned, and the set is not modified: original value is not replaced, and the value passed as argument is dropped.
Examples
use HashSet; let mut set = new; assert_eq!; assert_eq!; assert_eq!;- If the set did not previously contain this value,
fn replace(self: &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
use HashSet; let mut set = new; set.insert; assert_eq!; set.replace; assert_eq!;fn remove<Q>(self: &mut Self, value: &Q) -> bool where T: Borrow<Q>, Q: Hash + Eq + ?SizedRemoves a value from the set. Returns whether the value was present in the set.
The value may be any borrowed form of the set's value type, but
HashandEqon the borrowed form must match those for the value type.Examples
use HashSet; let mut set = new; set.insert; assert_eq!; assert_eq!;fn take<Q>(self: &mut Self, value: &Q) -> Option<T> where T: Borrow<Q>, Q: Hash + Eq + ?SizedRemoves and returns the value in the set, if any, that is equal to the given one.
The value may be any borrowed form of the set's value type, but
HashandEqon the borrowed form must match those for the value type.Examples
use HashSet; let mut set = from; assert_eq!; assert_eq!;
impl<T, S, A: Allocator> HashSet<T, S, A>
fn with_hasher_in(hasher: S, alloc: A) -> HashSet<T, S, A>Creates a new empty hash set which will use the given hasher to hash keys and will allocate memory using the provided allocator.
The hash set is also created with the default initial capacity.
Warning:
hasheris normally randomly generated, and is designed to allowHashSets 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_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> HashSet<T, S, A>Creates an empty
HashSetwith at least the specified capacity, usinghasherto hash the keys andallocto allocate memory.The hash set will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the hash set will not allocate.Warning:
hasheris normally randomly generated, and is designed to allowHashSets 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_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.fn capacity(self: &Self) -> usizeReturns the number of elements the set can hold without reallocating.
Examples
use HashSet; let set: = with_capacity; assert!;fn iter(self: &Self) -> Iter<'_, T>An iterator visiting all elements in arbitrary order. The iterator element type is
&'a T.Examples
use HashSet; let mut set = new; set.insert; set.insert; // Will print in an arbitrary order. for x in set.iterPerformance
In the current implementation, iterating over set takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
fn len(self: &Self) -> usizeReturns the number of elements in the set.
Examples
use HashSet; let mut v = new; assert_eq!; v.insert; assert_eq!;fn is_empty(self: &Self) -> boolReturns
trueif the set contains no elements.Examples
use HashSet; let mut v = new; assert!; v.insert; assert!;fn drain(self: &mut Self) -> Drain<'_, T, A>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
use HashSet; let mut set = from; assert!; // print 1, 2, 3 in an arbitrary order for i in set.drain assert!;fn extract_if<F>(self: &mut Self, pred: F) -> ExtractIf<'_, T, F, A> where F: FnMut(&T) -> boolCreates an iterator which uses a closure to determine if an element should be removed.
If the closure returns
true, the element is removed from the set and yielded. If the closure returnsfalse, or panics, the element remains in the set and will not be yielded.If the returned
ExtractIfis not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Useretainwith a negated predicate if you do not need the returned iterator.Examples
Splitting a set into even and odd values, reusing the original set:
use HashSet; let mut set: = .collect; let extracted: = set.extract_if.collect; let mut evens = extracted.into_iter.; let mut odds = set.into_iter.; evens.sort; odds.sort; assert_eq!; assert_eq!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(&T) -> boolRetains only the elements specified by the predicate.
In other words, remove all elements
efor whichf(&e)returnsfalse. The elements are visited in unsorted (and unspecified) order.Examples
use HashSet; let mut set = from; set.retain; assert_eq!;Performance
In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
fn clear(self: &mut Self)Clears the set, removing all values.
Examples
use HashSet; let mut v = new; v.insert; v.clear; assert!;fn hasher(self: &Self) -> &SReturns a reference to the set's
BuildHasher.Examples
use HashSet; use RandomState; let hasher = new; let set: = with_hasher; let hasher: &RandomState = set.hasher;
impl<'a, T, S, A> Extend for HashSet<T, S, A>
fn extend<I: IntoIterator<Item = &'a T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: &'a T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T> Any for HashSet<T, S, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for HashSet<T, S, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for HashSet<T, S, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for HashSet<T, S, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for HashSet<T, S, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for HashSet<T, S, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, N: usize> From for HashSet<T, RandomState>
fn from(arr: [T; N]) -> SelfConverts a
[T; N]into aHashSet<T>.If the array contains any equal values, all but one will be dropped.
Examples
use HashSet; let set1 = from; let set2: = .into; assert_eq!;
impl<T, S> Default for HashSet<T, S>
fn default() -> HashSet<T, S>Creates an empty
HashSet<T, S>with theDefaultvalue for the hasher.
impl<T, S> FromIterator for HashSet<T, S>
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S>
impl<T, S, A> Clone for HashSet<T, S, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, other: &Self)Overwrites the contents of
selfwith a clone of the contents ofsource.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.
impl<T, S, A> Debug for HashSet<T, S, A>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<T, S, A> Eq for HashSet<T, S, A>
impl<T, S, A> Extend for HashSet<T, S, A>
fn extend<I: IntoIterator<Item = T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T, S, A> Freeze for HashSet<T, S, A>
impl<T, S, A> PartialEq for HashSet<T, S, A>
fn eq(self: &Self, other: &HashSet<T, S, A>) -> bool
impl<T, S, A> RefUnwindSafe for HashSet<T, S, A>
impl<T, S, A> Send for HashSet<T, S, A>
impl<T, S, A> Sync for HashSet<T, S, A>
impl<T, S, A> Unpin for HashSet<T, S, A>
impl<T, S, A> UnsafeUnpin for HashSet<T, S, A>
impl<T, S, A> UnwindSafe for HashSet<T, S, A>
impl<T, S, A: Allocator> IntoIterator for HashSet<T, S, A>
fn into_iter(self: Self) -> IntoIter<T, A>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 HashSet; let mut set = new; set.insert; set.insert; // Not possible to collect to a Vec<String> with a regular `.iter()`. let v: = set.into_iter.collect; // Will print in an arbitrary order. for x in &v
impl<T, U> Into for HashSet<T, S, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for HashSet<T, S, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for HashSet<T, S, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>