Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Appendix A: Reference Summary

A compressed reference for the parts of Rust this book covers. The authority is the standard library documentation, available offline with rustup doc.

Keywords

as, async, await, break, const, continue, crate, dyn, else, enum, extern, false, fn, for, if, impl, in, let, loop, match, mod, move, mut, pub, ref, return, self, Self, static, struct, super, trait, true, type, unsafe, use, where, while.

Scalar Types

TypeMeaning
i8 i16 i32 i64 i128signed integers, default i32
u8 u16 u32 u64 u128unsigned integers
isize usizepointer-sized; usize indexes and measures
f32 f64floating point, default f64
booltrue or false, nothing converts to it
charone Unicode scalar value, four bytes
()the unit, value of an expression with no value
!never returns (return, break, panic!)

Compound Types

WrittenIs
(T, U)tuple, fields by position
[T; N]array, length in the type, no heap
&[T], &mut [T]slice, a borrowed view
Vec<T>growable array on the heap
String, &strowned and borrowed UTF-8 text
Option<T>Some(T) or None
Result<T, E>Ok(T) or Err(E)
Box<T>owned value on the heap
HashMap<K, V>, BTreeMap<K, V>maps, unordered and sorted
HashSet<T>, BTreeSet<T>sets, unordered and sorted

Ownership in One Table

WrittenMeans
x: Towns it; caller loses it when passed
x: &Tborrows to read; many may exist at once
x: &mut Tborrows to modify; only one may exist
x.clone()a deep copy, explicit and possibly expensive
move || ...closure takes ownership of what it captures
'aa lifetime: a region for which a reference is valid
'staticvalid for the whole program; every literal is

Formatting

println!, print!, eprintln!, format!, and write! share one language.

FormResult
{}Display, the user-facing form
{:?} {:#?}Debug, compact and multi-line
{name}the variable of that name
{:.3}three digits after the point
{:10.3} {:<10.3} {:^10.3}width ten: right, left, centered
{:width$}width taken from a variable
{:08}zero-padded to eight
{:+}always show the sign
{:b} {:o} {:x} {:X} {:#x}binary, octal, hex, upper hex, prefixed
{:e}scientific notation
{{ }}literal braces

Escapes inside string literals are \n, \t, \r, \0, \\, \", \', \u{1F980}. A raw string r"..." or r#"..."# takes no escapes at all.

Option and Result

MethodOn None / Err
unwrap()panics
expect("why")panics with your message
unwrap_or(v)gives v
unwrap_or_else(|| v)computes v only if needed
unwrap_or_default()gives the type’s default
map(f)leaves it alone
and_then(f)leaves it alone; f returns the same wrapper
ok_or(e)turns None into Err(e)
ok()turns Err into None
?returns it from the enclosing function

Iterators

Starting one: .iter() gives &T, .iter_mut() gives &mut T, .into_iter() consumes and gives T. A range a..b or a..=b is one, and so is a.. without end.

Adapters, which do nothing until consumed: map, filter, filter_map, take, take_while, skip, skip_while, step_by, rev, zip, enumerate, chain, flat_map, flatten, peekable, inspect, cloned, copied.

Consumers, which run the chain: collect, sum, product, count, fold, for_each, min, max, min_by_key, max_by_key, any, all, find, position, last, nth, partition.

Strings

Measuring is len() in bytes and chars().count() in characters. Walking is chars(), bytes(), char_indices(), lines(), split_whitespace(). Splitting is split, splitn, split_once, rsplit. Trimming is trim, trim_start, trim_end, trim_matches. Testing is contains, starts_with, ends_with, find, is_empty. Changing is to_lowercase, to_uppercase, replace, repeat, push_str, push. Converting is parse, to_string, as_str.

All indices are byte offsets, and slicing between character boundaries panics.

Attributes

AttributeEffect
#[derive(Debug, Clone, ...)]the compiler writes the implementation
#[test]a test function
#[cfg(test)]compile only when testing
#[should_panic]this test passes by panicking
#[allow(dead_code)]silence one lint here
#[must_use]warn if the return value is discarded
/// //!documentation for the next item, and for this module

Cargo

CommandDoes
cargo new, cargo new --libstart a program, start a library
cargo run, cargo run --bin xbuild and run
cargo build --releaseoptimized build
cargo checktype-check without producing a binary, much faster
cargo test, cargo test namerun tests, run matching tests
cargo fmtformat to the standard style
cargo clippylint, and learn the idioms
cargo doc --openbuild and read the documentation
cargo add nameadd a dependency
cargo treeshow what you have pulled in
rustc --explain E0382explain an error code