btree_map
import std::collections::btree_map; · source
Types
BTreeMap<K, V, A>
type struct BTreeMap<K, V, A = GlobalAllocator> where A: Allocator {
private root: mut BTreeNode<K, V>*;
private length: i64;
private alloc: A;
}
A map kept in key order, built as a B-tree. Keys need Ord rather than Hash; finding, inserting, and removing are O(log n). Each node holds up to eleven entries side by side, so a lookup compares against a run of neighbouring keys before it follows a pointer — a tree of n entries is about log₆(n) nodes deep — and every node but the root holds at least five.
Reach for it over HashMap when the order matters: iterating in key order, the smallest or greatest key, or every key in a range.
import std::collections::btree_map::{ BTreeMap };
import std::core::pair::{ Pair };
mut ages: BTreeMap<i64, i64> = BTreeMap::new();
ages.insert(30, 1);
ages.insert(10, 2);
ages.insert(20, 3);
for (entry in ages.entries()) {
// 10, then 20, then 30
}
const smallest: Option<Pair<i64*, i64*>> = ages.first();
const low: i64 = 15;
const from_15: i64 = ages.range(low..).count(); // 20 and 30
The access methods mirror HashMap's, though a lookup takes a reference to the key type itself: get reads by value and needs V: Copy, get_reference and get_mutable borrow, get_or_insert hands back a mut V*, insert returns the value it replaced, and remove returns the value (remove_entry the key too). first and last borrow the smallest and greatest entries; pop_first and pop_last take them out.
Constructors
static new() -> BTreeMap<K, V, GlobalAllocator>;
static new() -> BTreeMap<K, V, GlobalAllocator>;An empty map backed by GlobalAllocator. Allocates nothing until the first insert.
static new_in(alloc: A) -> BTreeMap<K, V, A>;
static new_in(alloc: A) -> BTreeMap<K, V, A>;An empty map that allocates through alloc.
Methods
length(&this) -> i64;
length(&this) -> i64;The number of keys in the map.
is_empty(&this) -> boolean;
is_empty(&this) -> boolean;True when the map holds no keys.
contains_key(&this, key: &K) -> boolean where K: Ord;
contains_key(&this, key: &K) -> boolean where K: Ord;True when the map holds key.
get(&this, key: &K) -> Option<V> where K: Ord, V: Copy;
get(&this, key: &K) -> Option<V> where K: Ord, V: Copy;A copy of the value for key, or None when the key is absent.
get_reference(&this, key: &K) -> Option<V*> where K: Ord;
get_reference(&this, key: &K) -> Option<V*> where K: Ord;A read-only borrow of the value for key, or None when the key is absent. Valid until the next insert or remove.
get_mutable(mut &this, key: &K) -> Option<mut V*> where K: Ord;
get_mutable(mut &this, key: &K) -> Option<mut V*> where K: Ord;A writable borrow of the value for key, or None when the key is absent. Valid until the next insert or remove.
insert(mut &this, key: K, value: V) -> Option<V> where K: Ord;
insert(mut &this, key: K, value: V) -> Option<V> where K: Ord;Insert key -> value. Returns the previous value if the key was present, otherwise None; a present key keeps the key it was inserted with. Panics on allocation failure; use try_insert to recover from it.
try_insert(mut &this, key: K, value: V) -> Result<Option<V>, AllocationError> where K: Ord;
try_insert(mut &this, key: K, value: V) -> Result<Option<V>, AllocationError> where K: Ord;insert that returns Err(AllocationError) instead of panicking when a node cannot be allocated. The map is unchanged by a failed insert.
get_or_insert(mut &this, key: K, default: V) -> mut V* where K: Ord;
get_or_insert(mut &this, key: K, default: V) -> mut V* where K: Ord;Borrow the value for key, inserting default first if the key is absent: one descent, unlike get_reference then insert. When the key is present, key and default are released. Panics on allocation failure.
try_get_or_insert(mut &this, key: K, default: V) -> Result<mut V*, AllocationError> where K: Ord;
try_get_or_insert(mut &this, key: K, default: V) -> Result<mut V*, AllocationError> where K: Ord;get_or_insert that returns Err(AllocationError) instead of panicking when a node cannot be allocated.
remove(mut &this, key: &K) -> Option<V> where K: Ord;
remove(mut &this, key: &K) -> Option<V> where K: Ord;Remove the entry for key. Returns its value, or None when the key was absent; the stored key is released.
remove_entry(mut &this, key: &K) -> Option<Pair<K, V>> where K: Ord;
remove_entry(mut &this, key: &K) -> Option<Pair<K, V>> where K: Ord;Remove the entry for key and hand back both its key and its value, or None when the key was absent.
first(&this) -> Option<Pair<K*, V*>>;
first(&this) -> Option<Pair<K*, V*>>;The entry with the smallest key, or None when empty.
last(&this) -> Option<Pair<K*, V*>>;
last(&this) -> Option<Pair<K*, V*>>;The entry with the greatest key, or None when empty.
pop_first(mut &this) -> Option<Pair<K, V>> where K: Ord;
pop_first(mut &this) -> Option<Pair<K, V>> where K: Ord;Remove and return the entry with the smallest key, or None when empty.
pop_last(mut &this) -> Option<Pair<K, V>> where K: Ord;
pop_last(mut &this) -> Option<Pair<K, V>> where K: Ord;Remove and return the entry with the greatest key, or None when empty.
clear(mut &this) -> void;
clear(mut &this) -> void;Release every entry and every node.
iter(&this) -> implement Iterator<Pair<K, V>> + DoubleEndedIterator where K: Copy, V: Copy;
iter(&this) -> implement Iterator<Pair<K, V>> + DoubleEndedIterator where K: Copy, V: Copy;Every entry by value, in ascending key order. Gated on K: Copy and V: Copy: the pairs are bit copies of the stored entries, which for an owning key or value would be released twice. entries walks any map by borrow.
keys(&this) -> implement Iterator<K> + DoubleEndedIterator where K: Copy;
keys(&this) -> implement Iterator<K> + DoubleEndedIterator where K: Copy;Every key by value, in ascending order. Gated on K: Copy, as iter is.
values(&this) -> implement Iterator<V> + DoubleEndedIterator where V: Copy;
values(&this) -> implement Iterator<V> + DoubleEndedIterator where V: Copy;Every value by value, in ascending key order. Gated on V: Copy, as iter is.
entries(&this) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIterator;
entries(&this) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIterator;Every entry as a borrowed key and value, in ascending key order: sound for any K and V, owning or not.
range<R>(&this, bounds: R) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIterator where K: Ord, R: RangeBounds<K>;
range<R>(&this, bounds: R) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIterator where K: Ord, R: RangeBounds<K>;The entries whose keys are in bounds, as borrowed keys and values, in ascending key order and from either end: map.range(low..high), map.range(low..=high), map.range(low..), map.range(..high), map.range(..), with bounds of the key type. Finding where the range starts and ends is O(log n).
key_references(&this) -> implement Iterator<K*> + DoubleEndedIterator;
key_references(&this) -> implement Iterator<K*> + DoubleEndedIterator;Every key by borrow, in ascending order.
value_references(&this) -> implement Iterator<V*> + DoubleEndedIterator;
value_references(&this) -> implement Iterator<V*> + DoubleEndedIterator;Every value by borrow, in ascending key order.
values_mutable(mut &this) -> implement Iterator<mut V*> + DoubleEndedIterator;
values_mutable(mut &this) -> implement Iterator<mut V*> + DoubleEndedIterator;Every value by writable borrow, in ascending key order: the way to change owning values in place.
Iterating
Iteration runs in ascending key order and from either end: every iterator here is a DoubleEndedIterator, so .reverse() walks the keys in descending order. iter(), keys(), and values() yield by value and need Copy; entries(), key_references(), and value_references() borrow and are sound for every key and value type, and values_mutable() yields mut V*. range(bounds) takes any range form over the key type — low..high, low..=high, low.., ..high, .. — through RangeBounds. An iterator borrows the map's storage and is invalidated by any insert or remove.
Trait implementations
implement<K, V, A> trait Drop for struct BTreeMap<K, V, A> where A: Allocator
implement<K, V> trait Clone for struct BTreeMap<K, V, GlobalAllocator> where K: Ord + Clone, V: Clone
implement<K, V> trait Default for struct BTreeMap<K, V, GlobalAllocator>
implement<K, V> trait FromIterator<Pair<K, V>> for struct BTreeMap<K, V, GlobalAllocator> where K: Ord
implement<K, V, A> trait Iterable for struct BTreeMap<K, V, A> where K: Copy, V: Copy, A: Allocator
implement<V> trait ToValue for struct BTreeMap<String<GlobalAllocator>, V, GlobalAllocator> where V: ToValue
std::encoding::value::convert
implement<V> trait FromValue for struct BTreeMap<String<GlobalAllocator>, V, GlobalAllocator> where V: FromValue
std::encoding::value::convert
implement<K, V, A> trait Display for struct BTreeMap<K, V, A> where K: Display, V: Display, A: Allocator
std::fmt::display
implement<K, V, A> trait Debug for struct BTreeMap<K, V, A> where K: Debug, V: Debug, A: Allocator
std::fmt::display
Clone is a deep copy, Default a fresh empty map that allocates nothing until the first insert, and collecting an iterator of Pair<K, V> builds one.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct BTreeMap<K, V, A = GlobalAllocator> where A: Allocator {}A map from keys to values kept in ascending key order. Keys need Ord. Lookups and inserts take time logarithmic in the size; iteration and range visit keys in order.
type parameter Ktype parameter Vtype parameter Awhere A: Allocator
type struct GlobalAllocator {}Zero-sized handle to the process-wide allocator. Construct with GlobalAllocator::new(); all instances dispatch through the same underlying backend.
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait Allocator {
allocate(mut &this, layout: Layout) -> Result<NonNull<u8>, AllocationError>;
deallocate(mut &this, ptr: NonNull<u8>, layout: Layout) -> void;
reallocate(mut &this, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<u8>, AllocationError>;
}A source of heap memory: hands out blocks described by a Layout and takes them back. Collections, Box and String take an A: Allocator type parameter, so the storage strategy is the caller's choice; GlobalAllocator is the default.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
BTreeMap.root: mut BTreeNode<K, V>*mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
type parameter Ktype parameter VBTreeMap.length: i64BTreeMap.alloc: Aimport a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::collections::btree_map;BTreeMap<K, V, A>: a map kept in key order, built as a B-tree.
module pagetype struct BTreeMap<K, V, A = GlobalAllocator> where A: Allocator {}A map from keys to values kept in ascending key order. Keys need Ord. Lookups and inserts take time logarithmic in the size; iteration and range visit keys in order.
type struct Pair<A, B> with [Eq, Clone] {
first: A;
second: B;
}Two values held together, first and second: a map's key with its value.
mut ages: BTreeMap<i64, i64>static BTreeMap::new() -> BTreeMap<K, V, GlobalAllocator>An empty map backed by GlobalAllocator. Allocates nothing until the first insert.
mut ages: BTreeMap<i64, i64>BTreeMap::insert(mut &this, key: K, value: V) -> Option<V>
where K: OrdInsert key -> value. Returns the previous value if the key was present, otherwise None; a present key keeps the key it was inserted with. Panics on allocation failure; use try_insert to recover from it.
for (mut i: i32 = 0; i < n; i++) { ... }
for (item in iterable) { ... }
for ((i, item) in items.iterate().enumerate()) { ... }Two forms. The C-style for (init; condition; step) scopes its loop variable to the body. for (x in expr) iterates an Iterator, a range such as 0..n, or an Iterable, which it consumes: an Array, a Slice of Copy elements, or a fixed-size array. A loop that only borrows writes its borrowing iterator, xs.iter() or xs.iterate_references(). The binding may be a tuple pattern that takes each item apart, nested and with _ elements: enumerate() yields (index, element) with an i64 index, and zip yields (a, b). A loop variable the body never reads is warned about (W0001); write _.
entry: Pair<i64*, i64*>for (item in iterable) { ... }Separates the loop variable from the sequence in a for loop. The sequence is evaluated once; the loop lowers to loop { match (it.next()) { Some(x) => .., None => break } }.
BTreeMap::entries(&this) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIteratorEvery entry as a borrowed key and value, in ascending key order: sound for any K and V, owning or not.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const smallest: Option<Pair<i64*, i64*>>type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
BTreeMap::first(&this) -> Option<Pair<K*, V*>>The entry with the smallest key, or None when empty.
const low: i64const from_15: i64BTreeMap::range<R>(&this, bounds: R) -> implement Iterator<Pair<K*, V*>> + DoubleEndedIterator
where K: Ord, R: RangeBounds<K>The entries whose keys are in bounds, as borrowed keys and values, in ascending key order and from either end: map.range(low..high), map.range(low..=high), map.range(low..), map.range(..high), map.range(..), with bounds of the key type. Finding where the range starts and ends is O(log n).
const low: i64start..endA half-open range - start up to but excluding end - and sugar for Range::new(start, end): an iterator usable in for, and an ordinary value anywhere else. It binds looser than arithmetic, so a..b + 1 is a..(b + 1).
Iterator::count(mut &this) -> i64Number of remaining elements. The default walks the iterator to count, consuming it. Implementations with O(1) knowledge of their length should override.
std::core::itertype trait Ord : Eq {
compare(&this, other: &This) -> Ordering;
}Types that have a total order: every pair is Less, Equal, or Greater. compare must be consistent with equals: if a.equals(b) then a.compare(b) == Equal.
type trait Hash {
hash<H>(&this, hasher: mut &H) -> void
where H: Hasher;
}A type whose values can be hashed, so they can key a HashMap or sit in a HashSet. Values that are equal under Eq must feed the same bytes. A type takes it with with [Hash] on its declaration, or by implementing hash by hand.
type struct HashMap<K, V, A = GlobalAllocator, H = SipHasher> where A: Allocator {}A map from keys to values, found by the key's hash. Keys need Hash and Eq. H is the hasher: SipHasher by default, which resists keys chosen to collide; FnvHasher is faster for trusted keys. Iteration order is unspecified; BTreeMap keeps keys sorted.
BTreeMap::get(&this, key: &K) -> Option<V>
where K: Ord, V: CopyA copy of the value for key, or None when the key is absent.
type trait Copy {}Types whose values can be duplicated by a bitwise copy. Integers, floats, pointers, and pure-POD structs qualify; anything that owns resources (heap storage, file handles, refcount) does not.
std::core::markerBTreeMap::get_reference(&this, key: &K) -> Option<V*>
where K: OrdA read-only borrow of the value for key, or None when the key is absent. Valid until the next insert or remove.
BTreeMap::get_mutable(mut &this, key: &K) -> Option<mut V*>
where K: OrdA writable borrow of the value for key, or None when the key is absent. Valid until the next insert or remove.
BTreeMap::get_or_insert(mut &this, key: K, default: V) -> mut V*
where K: OrdBorrow the value for key, inserting default first if the key is absent: one descent, unlike get_reference then insert. When the key is present, key and default are released. Panics on allocation failure.
mut VBTreeMap::remove(mut &this, key: &K) -> Option<V>
where K: OrdRemove the entry for key. Returns its value, or None when the key was absent; the stored key is released.
BTreeMap::remove_entry(mut &this, key: &K) -> Option<Pair<K, V>>
where K: OrdRemove the entry for key and hand back both its key and its value, or None when the key was absent.
BTreeMap::last(&this) -> Option<Pair<K*, V*>>The entry with the greatest key, or None when empty.
BTreeMap::pop_first(mut &this) -> Option<Pair<K, V>>
where K: OrdRemove and return the entry with the smallest key, or None when empty.
BTreeMap::pop_last(mut &this) -> Option<Pair<K, V>>
where K: OrdRemove and return the entry with the greatest key, or None when empty.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static BTreeMap::new_in(alloc: A) -> BTreeMap<K, V, A>An empty map that allocates through alloc.
(parameter) alloc: A&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
BTreeMap::contains_key(&this, key: &K) -> boolean
where K: OrdTrue when the map holds key.
(parameter) key: &KOption::Nonemut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
(parameter) key: K(parameter) value: VBTreeMap::try_insert(mut &this, key: K, value: V) -> Result<Option<V>, AllocationError>
where K: Ordinsert that returns Err(AllocationError) instead of panicking when a node cannot be allocated. The map is unchanged by a failed insert.
type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
type struct AllocationError {
kind: AllocationErrorKind;
layout: Layout;
}The error an Allocator returns: what went wrong (kind) and the layout that was requested when it did (layout; for a reallocate, the new layout).
Result::Err(E)(parameter) default: V// reservedOpens no form of the language: a declaration or member written with it is refused where it is written (E0117). It still names a method: Default::default() is the trait's constructor.
BTreeMap::try_get_or_insert(mut &this, key: K, default: V) -> Result<mut V*, AllocationError>
where K: Ordget_or_insert that returns Err(AllocationError) instead of panicking when a node cannot be allocated.
BTreeMap::iter(&this) -> implement Iterator<Pair<K, V>> + DoubleEndedIterator
where K: Copy, V: CopyEvery entry by value, in ascending key order. Gated on K: Copy and V: Copy: the pairs are bit copies of the stored entries, which for an owning key or value would be released twice. entries walks any map by borrow.
-> implement Trait<T>An opaque type: some one concrete type that implements the trait, without naming it. The compiler infers the real type and uses it everywhere; callers see only the trait's methods. How the stdlib returns iterators without exposing their engines.
language referencetype trait Iterator {
type Item;
next(mut &this) -> Option<This::Item>;
count(mut &this) -> i64;
fold<Acc, F>(mut &this, initial: Acc, f: F) -> Acc
where F: (Acc, This::Item) -> Acc;
for_each<F>(mut &this, f: F) -> void
where F: (This::Item) -> void;
take(this, n: i64) -> implement Iterator<This::Item>;
skip(this, n: i64) -> implement Iterator<This::Item>;
map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> B;
filter<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
chain<J>(this, other: J) -> implement Iterator<This::Item>
where J: Iterator<This::Item>;
enumerate(this) -> implement Iterator<(i64, This::Item)>;
zip<J>(this, other: J) -> implement Iterator<(This::Item, J::Item)>
where J: Iterator;
collect<C>(this) -> C
where C: FromIterator<This::Item>;
sum<S>(this) -> S
where S: Sum, This: Iterator<S>;
reverse(this) -> implement Iterator<This::Item>
where This: DoubleEndedIterator;
peekable(this) -> implement Peekable<This::Item>;
flat_map<B, F>(this, f: F) -> implement Iterator<B::Item>
where F: (This::Item) -> B, B: Iterator;
flatten(this) -> implement Iterator<This::Item::Item>
where This::Item: Iterator;
take_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
skip_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
step_by(this, step: i64) -> implement Iterator<This::Item>;
filter_map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> Option<B>;
any<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
all<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
find<P>(mut &this, pred: P) -> Option<This::Item>
where P: (&This::Item) -> boolean;
min(mut &this) -> Option<This::Item>
where This::Item: Ord;
max(mut &this) -> Option<This::Item>
where This::Item: Ord;
min_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
max_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
min_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
max_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
last(mut &this) -> Option<This::Item>;
nth(mut &this, n: i64) -> Option<This::Item>;
position<P>(mut &this, pred: P) -> Option<i64>
where P: (This::Item) -> boolean;
product<S>(this) -> S
where S: Product, This: Iterator<S>;
}A source of values handed out one at a time by next, until it returns None. for (x in source) drives one, and the adapter methods below build new iterators from it:
type trait DoubleEndedIterator : Iterator {
next_back(mut &this) -> Option<This::Item>;
}An iterator that also yields from its back end. next and next_back draw from one sequence, so between them each element is yielded once.
BTreeMap::keys(&this) -> implement Iterator<K> + DoubleEndedIterator
where K: CopyEvery key by value, in ascending order. Gated on K: Copy, as iter is.
BTreeMap::values(&this) -> implement Iterator<V> + DoubleEndedIterator
where V: CopyEvery value by value, in ascending key order. Gated on V: Copy, as iter is.
(parameter) bounds: Rtype trait RangeBounds<T> {
start_bound(&this) -> Bound<&T>;
end_bound(&this) -> Bound<&T>;
}A range over an ordered T, whichever range form wrote it: a..b, a..=b, a.., ..b or ... A method that takes a range of keys (BTreeMap.range) takes any of them through this trait. The full range .. names no T and is a range of every T: a call through the bound takes T from the bound's argument.
const low: i64start..=endAn inclusive range - start through end - and sugar for RangeInclusive::new(start, end). Also a match pattern: 1..=5 => { ... }.
BTreeMap::key_references(&this) -> implement Iterator<K*> + DoubleEndedIteratorEvery key by borrow, in ascending order.
std::collections::btree_mapBTreeMap::value_references(&this) -> implement Iterator<V*> + DoubleEndedIteratorEvery value by borrow, in ascending key order.
std::collections::btree_mapBTreeMap::values_mutable(mut &this) -> implement Iterator<mut V*> + DoubleEndedIteratorEvery value by writable borrow, in ascending key order: the way to change owning values in place.
std::collections::btree_mapimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
type trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype parameter Kwhere K: Ord + Clone
type parameter Vwhere V: Clone
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
type trait Default {
static default() -> This;
}A type with a canonical starting value, which generic code can make without knowing the type: 0 for the numbers, false, '\0', and an empty value for the collections that implement it.
type parameter Kwhere K: Ord
type trait FromIterator<T> {
static from_iterator<I>(source: I) -> This
where I: Iterator<T>;
}A collection built from the elements of an iterator: what collect builds.
type parameter Kwhere K: Copy
type parameter Vwhere V: Copy
type trait Iterable {
type Iteration;
iterate(this) -> This::Iteration;
}A value a for loop can loop over that is not itself an Iterator: the loop consumes it, iterate turns it into the iterator the loop drives, and each element is handed to the body as a value of its own.
type parameter Vwhere V: ToValue
type trait ToValue {
to_value(&this) -> Value;
}A value that can be written as a Value.
type struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
type parameter Vwhere V: FromValue
type trait FromValue {
static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}A value that can be read from a Value.
type parameter Kwhere K: Display
type parameter Vwhere V: Display
type trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.
type parameter Kwhere K: Debug
type parameter Vwhere V: Debug
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.