Rust Language quick reference
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
let x = 5;let mut x = 5;&x / &mut x
match v { ... }Option<T> / Result<T, E>
expr?impl Trait for Type
#[derive(Debug)]
Concepts
- Owner one variable owns the value
- New owner old binding unusable
- Borrow many &T or one &mut T
- Drop memory freed, no GC
Bindings and types
let <x> = <v>;
let mut <x> = <v>;
let <x>: <T> = <v>;
i32 u8 usize f64 bool char
&[<T>]
&str / String
Vec<T>Functions and control flow
fn <name>(<a>: <T>) -> <R> { ...
}
|<x>| <expr>
move |<x>| <expr>
if <c> { ... } else { ... }
if let <pat> = <v> { ... }
for <x> in <iter> { ... }
0..<n> / 0..=<n>
Structs and enums
struct <S> { <f>: <T> }
enum <E> { <A>, <B>(<T>), <C>
{ <f>: <U> } }
impl <S> { fn <new>() -> Self { ... }
}
&self / &mut self / self
#[derive(Debug, Clone, PartialEq)]
Pattern matching
match <v> { <pat> => <expr>, _ =>
<expr> }
Some(<x>) / None
Ok(<v>) / Err(<e>)
Ownership and references
&<x>&mut <x>
<x>.clone()
<'a>&'static <T>
Box<T>Rc<T> / Arc<T>
RefCell<T>
Mutex<T>Option and Result
<opt>.unwrap_or(<d>)
<x>.map(|<v>| ...)
<x>.and_then(|<v>| ...)
<x>.unwrap() / .expect("<msg>")
<res>.map_err(|<e>| ...)
<opt>.as_ref() / .as_mut()
<x>?Traits and generics
trait <T> { fn <m>(&self) -> <R>;
}
impl <Tr> for <S> { ... }
fn <f><T: <Tr>>(<x>: T)
fn <f>(<x>: &impl <Tr>)
where <T>: <A> + <B>,
struct <S><T> { <f>: T }
Box<dyn <Tr>>
impl Iterator for <S> { type Item = <T>; ...
}
Collections and iterators
vec![<a>, <b>]
<v>.push(<x>) / <v>.pop()
<v>[<i>] / <v>.get(<i>)
<v>.iter() / .iter_mut() / .into_iter()
<it>.map(|<x>| ...)
<it>.filter(|<x>| ...)
<it>.collect::<Vec<_>>()
<it>.enumerate()
<it>.collect::<Result<Vec<_>,
_>>()
HashMap::new() / .insert(<k>, <v>)
<m>.entry(<k>).or_insert(<d>)
Strings
String::from("<s>") /
"<s>".to_string()
format!("{} {}", <a>, <b>)
println!("{<x>}")
{:?} / {:#?}&<s>[<a>..<b>]
Modules and crates
mod <name>;
pub fn / pub struct
use <path>::<Item>;
#[cfg(test)]Concurrency and unsafe
thread::spawn(move || { ... })
Arc<Mutex<T>>
async fn / .await
unsafe { ... }Testing and docs
#[test] fn <name>() { ... }
assert!(<c>) / assert_eq!(<a>, <b>)
/// <text>
Recipes
fn read(p: &str) -> Result<String, io::Error> { let s = fs::read_to_string(p)?; Ok(s.trim().to_string())}
let mut n: HashMap<&str, usize> = HashMap::new();for w in text.split_whitespace() { *n.entry(w).or_insert(0) += 1;}
let c = Arc::new(Mutex::new(0));let c2 = Arc::clone(&c);let h = thread::spawn(move || *c2.lock().unwrap() += 1);h.join().unwrap();
match shape { Shape::Circle(r) => 3.14 * r * r, Shape::Rect(w, h) => w * h,}



