Rust Language quick reference

Version 1.97 · source

Start here

let x = 5;
Immutable binding
let mut x = 5;
Mutable binding
&x / &mut x
Borrow shared / exclusive
match v { ... }
Exhaustive branching
Option<T> / Result<T, E>
No null, no exceptions
expr?
Propagate the error
impl Trait for Type
Implement behaviour
#[derive(Debug)]
Generate trait impls

Concepts

  1. Owner one variable owns the value
  2. New owner old binding unusable
  3. Borrow many &T or one &mut T
  4. Drop memory freed, no GC
Ownership: move, borrow, drop

Bindings and types

let <x> = <v>;
Immutable binding (shadowing allowed)
let mut <x> = <v>;
Mutable binding
let <x>: <T> = <v>;
Annotate the type
i32 u8 usize f64 bool char
Common scalar types
&[<T>]
Slice: borrowed view of a sequence
&str / String
Borrowed text / owned growable text
Vec<T>
Growable list

Functions and control flow

fn <name>(<a>: <T>) -> <R> { ... }
Define a function
|<x>| <expr>
Closure
move |<x>| <expr>
Closure that takes ownership of captures
if <c> { ... } else { ... }
Conditional, usable as an expression
if let <pat> = <v> { ... }
Run when one pattern matches
for <x> in <iter> { ... }
Iterate a collection or range
0..<n> / 0..=<n>
Range, end exclusive / inclusive

Structs and enums

struct <S> { <f>: <T> }
Struct with named fields
enum <E> { <A>, <B>(<T>), <C> { <f>: <U> } }
Enum with data per variant
impl <S> { fn <new>() -> Self { ... } }
Add methods and associated functions
&self / &mut self / self
Method receiver: borrow / mutate / consume
#[derive(Debug, Clone, PartialEq)]
Auto-implement common traits

Pattern matching

match <v> { <pat> => <expr>, _ => <expr> }
Exhaustive branching
Some(<x>) / None
Option variants
Ok(<v>) / Err(<e>)
Result variants

Ownership and references

&<x>
Shared borrow (read only)
&mut <x>
Exclusive borrow (read and write)
<x>.clone()
Deep copy, explicit
<'a>
Lifetime parameter, as in fn f<'a>(x: &'a str)
&'static <T>
Reference valid for the whole program
Box<T>
Heap allocation, single owner
Rc<T> / Arc<T>
Shared ownership, single / multi thread
RefCell<T>
Interior mutability checked at runtime
Mutex<T>
Lock-protected data across threads

Option and Result

<opt>.unwrap_or(<d>)
Value or a default
<x>.map(|<v>| ...)
Transform the inner value
<x>.and_then(|<v>| ...)
Chain a step that may fail
<x>.unwrap() / .expect("<msg>")
Panic if None or Err
<res>.map_err(|<e>| ...)
Convert the error type
<opt>.as_ref() / .as_mut()
Borrow the inner value
<x>?
Return early on None or Err

Traits and generics

trait <T> { fn <m>(&self) -> <R>; }
Define shared behaviour
impl <Tr> for <S> { ... }
Implement a trait for a type
fn <f><T: <Tr>>(<x>: T)
Generic function with a bound
fn <f>(<x>: &impl <Tr>)
Shorthand for a trait bound
where <T>: <A> + <B>,
Bounds on a separate line
struct <S><T> { <f>: T }
Generic struct
Box<dyn <Tr>>
Trait object, dynamic dispatch
impl Iterator for <S> { type Item = <T>; ... }
Make your own iterator

Collections and iterators

vec![<a>, <b>]
Vec literal
<v>.push(<x>) / <v>.pop()
Append / remove last
<v>[<i>] / <v>.get(<i>)
Index (panics) / checked (Option)
<v>.iter() / .iter_mut() / .into_iter()
Borrow / mutably borrow / consume
<it>.map(|<x>| ...)
Transform each item
<it>.filter(|<x>| ...)
Keep matching items
<it>.collect::<Vec<_>>()
Gather into a collection
<it>.enumerate()
Pair items with an index
<it>.collect::<Result<Vec<_>, _>>()
Stop at the first error
HashMap::new() / .insert(<k>, <v>)
Key-value map
<m>.entry(<k>).or_insert(<d>)
Insert if missing, get a &mut

Strings

String::from("<s>") / "<s>".to_string()
Owned String from a literal
format!("{} {}", <a>, <b>)
Build a String
println!("{<x>}")
Print with inline variable
{:?} / {:#?}
Debug / pretty Debug formatting
&<s>[<a>..<b>]
Substring by byte range
Panics if the range cuts a multi-byte character.

Modules and crates

mod <name>;
Declare a module (src/<name>.rs)
pub fn / pub struct
Make an item public
use <path>::<Item>;
Import a name
#[cfg(test)]
Compile only for tests

Concurrency and unsafe

thread::spawn(move || { ... })
Run a closure on a new thread
Arc<Mutex<T>>
Shared mutable state across threads
async fn / .await
Async function and suspension point
Needs an executor such as tokio; std has none.
unsafe { ... }
Block that may deref raw pointers, call unsafe fns

Testing and docs

#[test] fn <name>() { ... }
Mark a test function
assert!(<c>) / assert_eq!(<a>, <b>)
Fail the test on mismatch
/// <text>
Doc comment on the next item

Recipes

Error type with ?
fn read(p: &str) -> Result<String, io::Error> {    let s = fs::read_to_string(p)?;    Ok(s.trim().to_string())}
Count words with a HashMap
let mut n: HashMap<&str, usize> = HashMap::new();for w in text.split_whitespace() {    *n.entry(w).or_insert(0) += 1;}
Shared counter across threads
let c = Arc::new(Mutex::new(0));let c2 = Arc::clone(&c);let h = thread::spawn(move || *c2.lock().unwrap() += 1);h.join().unwrap();
Enum with match
match shape {    Shape::Circle(r) => 3.14 * r * r,    Shape::Rect(w, h) => w * h,}