Struct HashSet
struct HashSet<T, S = crate::DefaultHashBuilder, A: Allocator = self::inner::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.
It is a logic error for an item to be modified in such a way that the
item's hash, as determined by the Hash trait, or its equality, as
determined by the Eq trait, changes while it is in the set. This is
normally only possible through Cell, RefCell, global state, I/O, or
unsafe code.
It is also a logic error for the Hash implementation of a key to panic.
This is generally only possible if the trait is implemented manually. If a
panic does occur then the contents of the HashSet may become corrupted and
some items may be dropped from the table.
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. This will in the
future be implied by Eq.
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 fixed list of elements can be initialized from an array:
use HashSet;
let viking_names: =
.into_iter.collect;
// use the values stored in the set
Implementations
impl<T, S> HashSet<T, S, Global>
const fn with_hasher(hasher: S) -> SelfCreates a new empty hash set which will use the given hasher to hash keys.
The hash set is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashSetto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashSet.The
hash_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use DefaultHashBuilder; let s = default; let mut set = with_hasher; set.insert;fn with_capacity_and_hasher(capacity: usize, hasher: S) -> SelfCreates an empty
HashSetwith the specified capacity, usinghasherto hash the keys.The hash set will be able to hold at least
capacityelements without reallocating. Ifcapacityis 0, the hash set will not allocate.HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashSetto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashSet.The
hash_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use DefaultHashBuilder; let s = default; 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 avoid frequent reallocations.Panics
Panics if the new capacity exceeds
isize::MAXbytes andabortthe program in case of allocation error. Usetry_reserveinstead if you want to handle memory allocation failure.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 the givenHashSet<K,V>. The collection may reserve more space to avoid frequent reallocations.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.
Panics if the current capacity is smaller than the supplied minimum capacity.
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 Self) -> 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: = .into_iter.collect; let b: = .into_iter.collect; // 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 Self) -> 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: = .into_iter.collect; let b: = .into_iter.collect; // 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 Self) -> Intersection<'a, T, S, A>Visits the values representing the intersection, i.e., the values that are both in
selfandother.Examples
use HashSet; let a: = .into_iter.collect; let b: = .into_iter.collect; // 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 Self) -> 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: = .into_iter.collect; let b: = .into_iter.collect; // 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 Q: Hash + Equivalent<T> + ?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: = .into_iter.collect; assert_eq!; assert_eq!;fn get<Q>(self: &Self, value: &Q) -> Option<&T> where Q: Hash + Equivalent<T> + ?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: = .into_iter.collect; 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: = .into_iter.collect; 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 Q: Hash + Equivalent<T> + ?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 insertedThe following example will panic because the new value doesn't match.
let mut set = hashbrown::HashSet::new(); set.get_or_insert_with("rust", |_| String::new());fn 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: &Self) -> boolReturns
trueifselfhas no elements in common withother. This is equivalent to checking for an empty intersection.Examples
use HashSet; let a: = .into_iter.collect; let mut b = new; assert_eq!; b.insert; assert_eq!; b.insert; assert_eq!;fn is_subset(self: &Self, other: &Self) -> boolReturns
trueif the set is a subset of another, i.e.,othercontains at least all the values inself.Examples
use HashSet; let sup: = .into_iter.collect; let mut set = new; assert_eq!; set.insert; assert_eq!; set.insert; assert_eq!;fn is_superset(self: &Self, other: &Self) -> boolReturns
trueif the set is a superset of another, i.e.,selfcontains at least all the values inother.Examples
use HashSet; let sub: = .into_iter.collect; 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.
If the set did not have this value present,
trueis returned.If the set did have this value present,
falseis returned.Examples
use HashSet; let mut set = new; assert_eq!; assert_eq!; assert_eq!;unsafe fn insert_unique_unchecked(self: &mut Self, value: T) -> &TInsert a value the set without checking if the value already exists in the set.
This operation is faster than regular insert, because it does not perform lookup before insertion.
This operation is useful during initial population of the set. For example, when constructing a set from another set, we know that values are unique.
Safety
This operation is safe if a value does not exist in the set.
However, if a value exists in the set already, the behavior is unspecified: this operation may panic, loop forever, or any following operation with the set may panic, loop forever or return arbitrary result.
That said, this operation (and following operations) are guaranteed to not violate memory safety.
However this operation is still unsafe because the resulting
HashSetmay be passed to unsafe code which does expect the set to behave correctly, and would cause unsoundness as a result.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 Q: Hash + Equivalent<T> + ?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 Q: Hash + Equivalent<T> + ?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: = .into_iter.collect; assert_eq!; assert_eq!;fn allocation_size(self: &Self) -> usizeReturns the total amount of memory allocated internally by the hash set, in bytes.
The returned number is informational only. It is intended to be primarily used for memory profiling.
impl<T, S, A> HashSet<T, S, A>
fn allocator(self: &Self) -> &AReturns a reference to the underlying allocator.
const fn with_hasher_in(hasher: S, alloc: A) -> SelfCreates a new empty hash set which will use the given hasher to hash keys.
The hash set is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashSetto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashSet.The
hash_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use DefaultHashBuilder; let s = default; let mut set = with_hasher; set.insert;fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> SelfCreates an empty
HashSetwith the specified capacity, usinghasherto hash the keys.The hash set will be able to hold at least
capacityelements without reallocating. Ifcapacityis 0, the hash set will not allocate.HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashSetto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashSet.The
hash_builderpassed should implement theBuildHashertrait for theHashSetto be useful, see its documentation for details.Examples
use HashSet; use DefaultHashBuilder; let s = default; let mut set = with_capacity_and_hasher; set.insert;fn hasher(self: &Self) -> &SReturns a reference to the set's
BuildHasher.Examples
use HashSet; use DefaultHashBuilder; let hasher = default; let set: = with_hasher; let hasher: &DefaultHashBuilder = set.hasher;
impl<T, S, A: Allocator> HashSet<T, S, A>
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.iterfn 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 in an iterator.
Examples
use HashSet; let mut set: = .into_iter.collect; assert!; // print 1, 2, 3 in an arbitrary order for i in set.drain assert!;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
esuch thatf(&e)returnsfalse.Examples
use HashSet; let xs = ; let mut set: = xs.into_iter.collect; set.retain; assert_eq!;fn extract_if<F>(self: &mut Self, f: F) -> ExtractIf<'_, T, F, A> where F: FnMut(&T) -> boolDrains elements which are true under the given predicate, and returns an iterator over the removed items.
In other words, move all elements
esuch thatf(&e)returnstrueout into another iterator.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. Useretain()with a negated predicate if you do not need the returned iterator.Examples
use HashSet; let mut set: = .collect; let drained: = set.extract_if.collect; let mut evens = drained.into_iter.; let mut odds = set.into_iter.; evens.sort; odds.sort; assert_eq!; assert_eq!;fn clear(self: &mut Self)Clears the set, removing all values.
Examples
use HashSet; let mut v = new; v.insert; v.clear; assert!;
impl<'a, T, S, A> Extend for HashSet<T, S, A>
fn extend<I: IntoIterator<Item = &'a T>>(self: &mut Self, iter: I)
impl<Q, K> Equivalent for HashSet<T, S, A>
fn equivalent(self: &Self, key: &K) -> bool
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, S, A> BitAndAssign for HashSet<T, S, A>
fn bitand_assign(self: &mut Self, rhs: &HashSet<T, S, A>)Modifies this set to contain the intersection of
selfandrhs.Examples
use HashSet; let mut a: = vec!.into_iter.collect; let b: = vec!.into_iter.collect; a &= &b; let mut i = 0; let expected = ; for x in &a assert_eq!;
impl<T, S, A> BitOrAssign for HashSet<T, S, A>
fn bitor_assign(self: &mut Self, rhs: &HashSet<T, S, A>)Modifies this set to contain the union of
selfandrhs.Examples
use HashSet; let mut a: = vec!.into_iter.collect; let b: = vec!.into_iter.collect; a |= &b; let mut i = 0; let expected = ; for x in &a assert_eq!;
impl<T, S, A> BitXorAssign for HashSet<T, S, A>
fn bitxor_assign(self: &mut Self, rhs: &HashSet<T, S, A>)Modifies this set to contain the symmetric difference of
selfandrhs.Examples
use HashSet; let mut a: = vec!.into_iter.collect; let b: = vec!.into_iter.collect; a ^= &b; let mut i = 0; let expected = ; for x in &a assert_eq!;
impl<T, S, A> Debug for HashSet<T, S, A>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<T, S, A> Default for HashSet<T, S, A>
fn default() -> SelfCreates an empty
HashSet<T, S>with theDefaultvalue for the hasher.
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)
impl<T, S, A> Freeze for HashSet<T, S, A>
impl<T, S, A> From for HashSet<T, S, A>
fn from(map: HashMap<T, (), S, A>) -> Self
impl<T, S, A> FromIterator for HashSet<T, S, A>
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
impl<T, S, A> PartialEq for HashSet<T, S, A>
fn eq(self: &Self, other: &Self) -> 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> SubAssign for HashSet<T, S, A>
fn sub_assign(self: &mut Self, rhs: &HashSet<T, S, A>)Modifies this set to contain the difference of
selfandrhs.Examples
use HashSet; let mut a: = vec!.into_iter.collect; let b: = vec!.into_iter.collect; a -= &b; let mut i = 0; let expected = ; for x in &a assert_eq!;
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>
impl<T: Clone, S: Clone, A: Allocator + Clone> Clone for HashSet<T, S, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)