Reference Material
Iterator Methods and Adapters
next(&mut self) -> Option<Self::Item>Get the next element of an iterator (Noneif there isn't one)collect<B>(self) -> B-> Transforms the iterator into a collection of typeBtake(n: usize) -> Take<Self>-> Take first N elements of an iterator and turn them into an iteratorskip(n: usize) -> Skip<Self>-> Skip first N elements of an iterator and turn them into an iteratorcycle() -> Cycle<Self>-> Turn a finite iterator into an infinite one that repeats itselffor_each(|x| ...) -> ()-> Apply a closure to each element in the iteratorfilter(|x| ...) -> Filter<Self, P>-> Create new iterator from old one for elements where closure is truemap(|x| ...) -> Map<Self, F>-> Create new iterator by applying closure to input iteratorany(|x| ...) -> bool-> Returntrueif closure is true for any element of the iteratorfold(init: B, |acc, x| ...) -> B-> Initialize accumulator toinit, execute closure on each elementreduce(|acc, x| ...) -> Option<Self::Item>-> Similar to fold but the initial value is the first elementzip(other_iter) -> Zip<Self, U>-> Zip two iterators together into pairs of(a, b)enumerate() -> Enumerate<Self>-> Create iterator of(index, element)pairspartition(|x| ...) -> (B, B)-> Split iterator into two collections based on predicatesum() -> S-> Sum all elements (works on numeric iterators)count() -> usize-> Count the number of elements in the iteratorcopied() -> Copied<Self>-> Create iterator of owned copies from an iterator of referencesfind(|x| ...) -> Option<Self::Item>-> Return the first element for which the closure is true (Noneif none)
String and &str Methods
s.len() -> usize-> Number of bytes in the strings.contains("sub") -> bool->trueif string contains the substrings.to_uppercase() -> String-> Returns a newStringin uppercases.to_lowercase() -> String-> Returns a newStringin lowercases.push('c') -> ()-> Append a single character (mutatesString)s.push_str("text") -> ()-> Append a string slice (mutatesString)s.chars() -> Chars<'_>-> Iterator over the characters of the strings.split_whitespace() -> SplitWhitespace<'_>-> Iterator of substrings split by whitespaces.parse::<T>() -> Result<T, T::Err>-> Parse the string into typeTs.is_empty() -> bool->trueif the string has length 0
Vec Methods
v.push(val) -> ()-> Append element to the endv.pop() -> Option<T>-> Remove and return last elementv.get(i: usize) -> Option<&T>-> Safe bounds-checked accessv.len() -> usize-> Number of elementsv.is_empty() -> bool->trueif the vector has no elementsv.iter() -> Iter<'_, T>-> Iterator of immutable references&Tv.iter_mut() -> IterMut<'_, T>-> Iterator of mutable references&mut Tv.into_iter() -> IntoIter<T>-> Consuming iterator of owned valuesTv.sort() -> ()-> Sort in place in ascending order (requiresT: Ord)v.sort_by(|a, b| ...) -> ()-> Sort in place using a comparison closure (closure returnsOrdering)v.sort_by_key(|x| ...) -> ()-> Sort in place using a key functionv.contains(&x) -> bool->trueif the vector containsx(O(n) linear scan)v.to_vec() -> Vec<T>-> Copy a slice&[T]into a newVec<T>(requiresT: Clone)
Option Methods
opt.unwrap() -> T-> Extract the value or panic ifNoneopt.unwrap_or(default: T) -> T-> Extract the value or returndefault(eager)opt.unwrap_or_else(|| ...) -> T-> Extract the value or compute default via closure (lazy)opt.map(|x| ...) -> Option<U>-> Transform the inner value;NonestaysNoneopt.is_some() -> bool->trueifSomeopt.is_none() -> bool->trueifNone
Other Useful Methods
val.clone() -> T-> Create a deep copy of the valuea.cmp(&b) -> std::cmp::Ordering-> Compare two values; returnsOrdering::Less,Equal, orGreaterordering.then(other: Ordering) -> Ordering-> Useotheras a tiebreaker whenorderingisEqual(e.g.a.cmp(&b).then(x.cmp(&y)))val.into() -> U-> Convertvalinto typeUvia theInto/Fromtrait (e.g."text".into()produces aString)(x as f64).sqrt() -> f64-> Square root of a floating-point numberformat!("...", args) -> String-> Likeprintln!but returns aStringinstead of printingprint!("...", args)-> Likeprintln!but does not append a newline{:?}-> Debug format specifier (inprintln!/format!){:.2}-> Display with 2 decimal places
Test Assertion Macros
assert!(expr) -> ()-> Pass ifexpristrueassert_eq!(a, b) -> ()-> Pass ifa == b; shows both values on failureassert_ne!(a, b) -> ()-> Pass ifa != b; shows both values on failure- Assert macros can take an optional custom failure message, e.g.,
assert_eq!(a, b, "{} is not equal to {}", a, b).
HashMap Methods
Basic Operations:
new(): Creates an empty HashMap.insert(key, value) -> Option<V>: Adds a key-value pair to the map. If the map did not have the key thenNoneis returned, if the map did have the key the old value is returned asSome(V).remove(key) -> Option<V>: Removes a key-value pair from the map. If the map did not have the key thenNoneis returned, if the map did have the key the value is returned asSome(V).get(key) -> Option<&V>: Returns a reference to the value in the map, if any, that is equal to the given key. ReturnsNoneif the key is not present.contains_key(key) -> bool: Checks if the map contains a specific key. Returnstrueif present,falseotherwise.len() -> usize: Returns the number of key-value pairs in the map.is_empty() -> bool: Checks if the map contains no key-value pairs.clear(): Removes all key-value pairs from the map.drain(): Clears the map and returns all key-value pairs as an iterator.
Entry API:
entry(key).or_insert(value): Returns a mutable reference to the value in the map, if any, that is equal to the given key. If the key is not present, inserts the given value and returns a mutable reference to the new value.entry(key).or_insert_with(|| ...): Likeor_insert, but the default value is computed lazily from a closure (useful when construction is expensive, e.g.or_insert_with(Vec::new)).
Iterators and Views:
iter(): Returns an immutable iterator over the key-value pairs in the map.iter_mut(): Returns a mutable iterator over the key-value pairs in the map.into_iter(): Returns a consuming iterator of owned(key, value)pairs (moves the map).keys(): Returns an iterator over the keys in the map.values(): Returns an iterator over the values in the map.values_mut(): Returns a mutable iterator over the values in the map.
Indexing:
map[&key]: Returns a reference to the value forkey. Panics if the key is absent. Usegetfor a non-panicking alternative.
HashSet Methods
Basic Operations:
new(): Creates an empty HashSet.insert(value): Adds a value to the set. Returns true if the value was not present, false otherwise.remove(value): Removes a value from the set. Returns true if the value was present, false otherwise.contains(value): Checks if the set contains a specific value. Returns true if present, false otherwise.len(): Returns the number of elements in the set.is_empty(): Checks if the set contains no elements.clear(): Removes all elements from the set.drain(): Returns an iterator that removes all elements and yields them. The set becomes empty after this operation.
Entry API:
entry(value).or_insert(value): Returns a mutable reference to the value in the set, if any, that is equal to the given value. If the value is not present, inserts the given value and returns a mutable reference to the new value.
Set Operations:
union(&self, other: &HashSet<T>): Returns an iterator over the elements that are in self or other (or both).intersection(&self, other: &HashSet<T>): Returns an iterator over the elements that are in both self and other.difference(&self, other: &HashSet<T>): Returns an iterator over the elements that are in self but not in other.symmetric_difference(&self, other: &HashSet<T>): Returns an iterator over the elements that are in self or other, but not in both.is_subset(&self, other: &HashSet<T>): Checks if self is a subset of other.is_superset(&self, other: &HashSet<T>): Checks if self is a superset of other.is_disjoint(&self, other: &HashSet<T>): Checks if self has no elements in common with other.
Iterators and Views:
iter(): Returns an immutable iterator over the elements in the set.get(value): Returns a reference to the value in the set, if any, that is equal to the given value.
BTreeMap Methods
Basic Operations:
new(): Creates an empty BTreeMap.insert(key, value) -> Option<V>: Adds a key-value pair to the map. If the map did not have the key thenNoneis returned, if the map did have the key the old value is returned asSome(V).remove(key) -> Option<V>: Removes a key-value pair from the map. If the map did not have the key thenNoneis returned, if the map did have the key the value is returned asSome(V).get(key) -> Option<&V>: Returns a reference to the value in the map, if any, that is equal to the given key. ReturnsNoneif the key is not present.contains_key(key) -> bool: Checks if the map contains a specific key. Returnstrueif present,falseotherwise.len() -> usize: Returns the number of key-value pairs in the map.is_empty() -> bool: Checks if the map contains no key-value pairs.clear(): Removes all key-value pairs from the map.drain(): Clears the map and returns all key-value pairs as an iterator.
Entry API:
entry(key).or_insert(value): Returns a mutable reference to the value in the map, if any, that is equal to the given key. If the key is not present, inserts the given value and returns a mutable reference to the new value.entry(key).or_insert_with(|| ...): Likeor_insert, but the default value is computed lazily from a closure (e.g.or_insert_with(Vec::new)).
Iterators and Views:
iter(): Returns an immutable iterator over the key-value pairs in the map.iter_mut(): Returns a mutable iterator over the key-value pairs in the map.into_iter(): Returns a consuming iterator of owned(key, value)pairs (moves the map).keys(): Returns an iterator over the keys in the map.values(): Returns an iterator over the values in the map.values_mut(): Returns a mutable iterator over the values in the map.range(start..end): Returns an iterator over the key-value pairs in the map in the range[start, end).first_key_value(): Returns the first key-value pair in the map.last_key_value(): Returns the last key-value pair in the map.range(start..end): Returns an iterator over the key-value pairs in the map in the range[start, end).first_key_value(): Returns the first key-value pair in the map.last_key_value(): Returns the last key-value pair in the map.next(): Returns the next key-value pair in the map.next_back(): Returns the next key-value pair in the map in reverse order.
Indexing:
map[&key]: Returns a reference to the value forkey. Panics if the key is absent. Usegetfor a non-panicking alternative.
BTreeSet Methods
Basic Operations:
new(): Creates an empty BTreeSet.insert(value): Adds a value to the set. Returns true if the value was not present, false otherwise.remove(value): Removes a value from the set. Returns true if the value was present, false otherwise.contains(value): Checks if the set contains a specific value. Returns true if present, false otherwise.len(): Returns the number of elements in the set.is_empty(): Checks if the set contains no elements.clear(): Removes all elements from the set.drain(): Returns an iterator that removes all elements and yields them. The set becomes empty after this operation.
Entry API:
entry(value).or_insert(value): Returns a mutable reference to the value in the set, if any, that is equal to the given value. If the value is not present, inserts the given value and returns a mutable reference to the new value.
Set Operations:
union(&self, other: &BTreeSet<T>): Returns an iterator over the elements that are in self or other (or both).intersection(&self, other: &BTreeSet<T>): Returns an iterator over the elements that are in both self and other.difference(&self, other: &BTreeSet<T>): Returns an iterator over the elements that are in self but not in other.symmetric_difference(&self, other: &BTreeSet<T>): Returns an iterator over the elements that are in self or other, but not in both.is_subset(&self, other: &BTreeSet<T>): Checks if self is a subset of other.is_superset(&self, other: &BTreeSet<T>): Checks if self is a superset of other.is_disjoint(&self, other: &BTreeSet<T>): Checks if self has no elements in common with other.
Iterators and Views:
iter(): Returns an immutable iterator over the elements in the set.get(value): Returns a reference to the value in the set, if any, that is equal to the given value.range(start..end): Returns an iterator over the elements in the set in the range[start, end).first(): Returns the first element in the set.last(): Returns the last element in the set.next(): Returns the next element in the set.next_back(): Returns the next element in the set in reverse order.
BinaryHeap Methods (Max-Heap)
std::collections::BinaryHeap is a max-heap priority queue. Use std::cmp::Reverse to get a min-heap.
new(): Creates an emptyBinaryHeap.from(vals): Creates aBinaryHeapfrom an array or vector.from_iter(iter): Creates aBinaryHeapfrom an iterator.push(value) -> (): Inserts a value into the heap.pop() -> Option<T>: Removes and returns the largest element, orNoneif empty.peek() -> Option<&T>: Returns a reference to the largest element without removing it.len() -> usize: Number of elements.is_empty() -> bool:trueif the heap has no elements.iter(): Returns an iterator over the elements in arbitrary order (not sorted).into_sorted_vec() -> Vec<T>: Consumes the heap and returns aVecsorted in ascending order.
VecDeque Methods (Double-Ended Queue)
std::collections::VecDeque is a double-ended queue (ring buffer). Commonly used as a FIFO queue via push_back / pop_front.
new(): Creates an emptyVecDeque.push_back(value) -> (): Appends an element to the back.push_front(value) -> (): Prepends an element to the front.pop_back() -> Option<T>: Removes and returns the back element.pop_front() -> Option<T>: Removes and returns the front element.front() -> Option<&T>: Reference to the front element.back() -> Option<&T>: Reference to the back element.len() -> usize: Number of elements.is_empty() -> bool:trueif empty.iter(): Iterator from front to back.
LinkedList Methods
std::collections::LinkedList is a doubly-linked list.
new(): Creates an emptyLinkedList.push_back(value) -> (): Appends an element to the back.push_front(value) -> (): Prepends an element to the front.pop_back() -> Option<T>: Removes and returns the back element.pop_front() -> Option<T>: Removes and returns the front element.front() -> Option<&T>: Reference to the front element.back() -> Option<&T>: Reference to the back element.len() -> usize: Number of elements.is_empty() -> bool:trueif empty.iter(): Iterator from front to back.
Common Derivable Traits
Add with #[derive(...)] on a struct or enum:
Debug: Enables formatting with{:?}inprintln!/format!.Clone: Provides.clone()to produce a deep copy.Copy: Value is copied (bitwise) on assignment instead of moved. RequiresClone. Only valid for types whose fields are allCopy(e.g., noString, noVec<T>).PartialEq: Enables==and!=.Eq: Marker trait for total equality (noNaN-like values). RequiresPartialEq. Needed (withHash) forHashMap/HashSetkeys.PartialOrd: Enables<,<=,>,>=viapartial_cmp.Ord: Total ordering viacmp. RequiresEqandPartialOrd. Needed forBTreeMap/BTreeSetkeys andBinaryHeapelements.Hash: Enables use as aHashMap/HashSetkey. Typically combined withEq.Default: ProvidesT::default()that returns a default value.
Example:
#![allow(unused)] fn main() { #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct Point { x: i32, y: i32 } }