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
| Type | Meaning |
|---|---|
i8 i16 i32 i64 i128 | signed integers, default i32 |
u8 u16 u32 u64 u128 | unsigned integers |
isize usize | pointer-sized; usize indexes and measures |
f32 f64 | floating point, default f64 |
bool | true or false, nothing converts to it |
char | one Unicode scalar value, four bytes |
() | the unit, value of an expression with no value |
! | never returns (return, break, panic!) |
Compound Types
| Written | Is |
|---|---|
(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, &str | owned 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
| Written | Means |
|---|---|
x: T | owns it; caller loses it when passed |
x: &T | borrows to read; many may exist at once |
x: &mut T | borrows to modify; only one may exist |
x.clone() | a deep copy, explicit and possibly expensive |
move || ... | closure takes ownership of what it captures |
'a | a lifetime: a region for which a reference is valid |
'static | valid for the whole program; every literal is |
Formatting
println!, print!, eprintln!, format!, and write! share one language.
| Form | Result |
|---|---|
{} | 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
| Method | On 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
| Attribute | Effect |
|---|---|
#[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
| Command | Does |
|---|---|
cargo new, cargo new --lib | start a program, start a library |
cargo run, cargo run --bin x | build and run |
cargo build --release | optimized build |
cargo check | type-check without producing a binary, much faster |
cargo test, cargo test name | run tests, run matching tests |
cargo fmt | format to the standard style |
cargo clippy | lint, and learn the idioms |
cargo doc --open | build and read the documentation |
cargo add name | add a dependency |
cargo tree | show what you have pulled in |
rustc --explain E0382 | explain an error code |