Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 132 ยท Reference overview

Rust Reference: Keywords, std Types and Traits

A reference map of Rust: every keyword group, the standard library types you reach for, the traits that matter, how they relate and the macros you use daily.

The lessons in this tutorial teach Rust in order. This page is the opposite: a map you open when you already know roughly what you want and need the name. It lists the keywords, the standard library types and traits, and the common macros, groups them by purpose, and links each group to the lesson that explains it properly. It is the seed of a full Rust Reference section, with one page per keyword, type and trait, in the same style as the other reference sections on this site.

Two ideas make the standard library easy to hold in your head. First, nearly every type you use daily is in the prelude, so it needs no use: Option, Result, Vec, String, Box, and the traits Clone, Copy, Iterator, From, Into, Default, PartialEq, Ord and friends. Second, behavior comes from traits, so learning which traits a type implements tells you what it can do.

Keywords

Rust has three groups of keywords. Strict keywords are always reserved, so you cannot use them as names. Reserved keywords are held back for future use. Weak (contextual) keywords only act as keywords in certain positions.

Purpose Keywords
Bindings and items let, const, static, fn, struct, enum, trait, impl, type, mod, use, pub, crate, extern
Control flow if, else, match, loop, while, for, in, break, continue, return
References and mutability mut, ref, move, dyn, where, as
Paths self, Self, super, crate
Safety and async unsafe, async, await
Literals true, false
Reserved for the future abstract, become, box, do, final, gen, macro, override, priv, try, typeof, unsized, virtual, yield
Weak (contextual) union, macro_rules, raw, safe, 'static

If you need one of these words as an identifier, a raw identifier such as r#match escapes it. Reading about syntax, control flow and unsafe Rust covers the groups above in context.

Standard library types by job

Job Types Lesson
Optional and fallible values Option<T>, Result<T, E> Option, Result
Text String, &str, char, Cow<str>, OsString, PathBuf Strings
Growable and fixed sequences Vec<T>, [T; N], &[T], VecDeque<T>, LinkedList<T> Vec
Maps and sets HashMap, HashSet, BTreeMap, BTreeSet, BinaryHeap HashMap
Single ownership on the heap Box<T> Box
Shared ownership Rc<T>, Arc<T>, Weak<T> Rc and Arc
Interior mutability Cell<T>, RefCell<T>, OnceCell<T> RefCell
Threads and locks thread::spawn, Mutex<T>, RwLock<T>, Condvar, mpsc::channel, atomics Mutex and RwLock
Time and I/O Duration, Instant, SystemTime, File, BufReader, Path Files and I/O
Numbers i8 to i128, u8 to u128, isize, usize, f32, f64, NonZero<T>, Wrapping<T> Numbers

A good habit is to pick the simplest type that fits and move up only when you must: &str before String, Vec before VecDeque, Box before Rc, Rc before Arc, RefCell before Mutex. Each step to the right costs a little (an allocation, a counter, a lock) and buys a capability.

Traits that matter

You meet the same few dozen traits again and again.

Trait What it means Typical source
Debug Programmer-facing text with {:?} #[derive(Debug)]
Display User-facing text with {}; gives you to_string() written by hand
Clone Explicit deep copy with .clone() derive
Copy Implicit bitwise copy on assignment (requires Clone) derive, only for simple data
Default A sensible empty value, T::default() derive
PartialEq / Eq ==; Eq also promises a == a (no NaN-like values) derive
PartialOrd / Ord < and friends; Ord is a total order and enables sorting derive
Hash Can be a key in HashMap and HashSet derive
From / Into Infallible conversion; implement From, get Into free written by hand
TryFrom / TryInto Conversion that can fail written by hand
FromStr Powers "text".parse::<T>() written by hand
AsRef / Borrow Cheap reference-to-reference views written by hand
Deref / DerefMut Smart-pointer behavior and auto-deref smart pointers
Drop Clean-up code that runs when a value goes away written by hand
Iterator / IntoIterator Sequences and for loops written by hand
Fn, FnMut, FnOnce Closures and callable values automatic
Send / Sync Safe to move to, or share with, another thread automatic
Error A proper error type (needs Debug + Display) written by hand

Many of these are linked by supertraits: to implement one you must already implement another. Knowing the chain explains most "trait bound not satisfied" errors.

flowchart BT
    Eq --> PartialEq
    Ord --> Eq
    Ord --> PartialOrd
    PartialOrd --> PartialEq
    Copy --> Clone
    Error --> Debug
    Error --> Display
    Fn --> FnMut
    FnMut --> FnOnce

An arrow means "requires". Ord needs Eq and PartialOrd; Fn is the strictest closure trait and also satisfies FnMut and FnOnce.

Deriving a family of traits

#[derive] writes the standard implementation for you. The program below puts one small struct through most of the comparison traits, including the case where only PartialOrd exists.

Rust The derive family in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Field order matters for derive(PartialOrd, Ord): values compare by major first, then minor, which is why 1.10 is greater than 1.2 here. If you wrote the fields the other way round, the ordering would silently change.

Conversion traits

Rust has no implicit conversions between number or data types; you convert on purpose, and the conversion traits give every conversion a standard name. Use From when the conversion cannot fail, TryFrom when it can, and FromStr to parse text.

Rust From, TryFrom, FromStr, Display and AsRef

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Three rules of thumb follow from the example. Implement From, not Into; the standard library provides Into automatically. Implement FromStr if you want .parse() to work for your type. And accept impl AsRef<str> or impl Into<String> in function parameters when you want callers to pass either &str or String.

Macros you use every day

Macro Purpose
println!, print!, eprintln!, format!, write!, writeln! Formatting and output
vec! Build a Vec
assert!, assert_eq!, assert_ne!, debug_assert! Checks and tests
panic!, todo!, unimplemented!, unreachable! Stop the program with a message
matches! true if a value fits a pattern
dbg! Print an expression with its location and return it
include_str!, concat!, env!, cfg! Compile-time helpers
thread_local!, macro_rules! Declarations (the second defines your own macros)

The lessons on macros and testing cover writing your own and using the assertion family.

How to use this page

When a compiler error names a trait you do not know, find it in the traits table, check its supertraits, and then look for the matching derive or the lesson. When you are unsure which collection or pointer to pick, read the "types by job" table from left to right and take the first one that works. For quick syntax reminders rather than names, the cheat sheet is denser, and Reading Compiler Errors explains the messages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about Ord is true?

    Ord is a total order, so it requires Eq and PartialOrd. f64 only has PartialOrd because NaN is not comparable, which is why f64 values cannot be sorted with sort().
  2. 2. You implement From<Celsius> for Fahrenheit. What do you get for free?

    A blanket implementation in the standard library turns every From into the matching Into, so you should implement From and call .into().
  3. 3. Which trait do you implement so that "#ff8000".parse::<Rgb>() works?

    str::parse is defined in terms of FromStr. Display is the opposite direction (value to text).
  4. 4. What does Copy require?

    Copy is a marker with Clone as its supertrait, and it can only be implemented for types whose bits can be copied, so a type holding a String cannot be Copy.
  5. 5. Why are union, raw and macro_rules called weak keywords?

    Strict keywords are reserved everywhere. Weak keywords only have special meaning in particular syntax, which kept old code compiling when they were added.

Summary

  • Keywords come in strict, reserved and weak groups; use a raw identifier (r#match) if you need one as a name.
  • Choose the simplest standard type for the job, and step up (String, Rc, Arc, Mutex) only when you need what it adds.
  • Traits describe behavior; supertraits form chains (Ord needs Eq and PartialOrd, Copy needs Clone, Fn implies FnMut and FnOnce).
  • Derive the common traits; field order decides derived ordering.
  • Convert on purpose: From for infallible, TryFrom for fallible, FromStr for parsing, AsRef for flexible parameters.
  • Macros end in !; the formatting, assertion and panic families cover most daily needs.

Back to the quick syntax overview: Rust Cheat Sheet