Rust Language Cheat Sheet PDF
Rust Language Cheat Sheet PDF
Contains clickable links to The Book BK, Rust by Example EX, Std Docs STD, Nomicon NOM, Reference REF. Other symbols used:
largely deprecated 🗑, has a minimum edition '18, is work in progress 🚧, or bad 🛑.
Data Structures
Data types and memory locations de ned via keywords.
Example Explanation
struct S {} De ne a struct BK EX STD REF with named elds.
struct S; De ne zero sized NOM unit struct. Occupies no space, optimized away.
enum E { A, B (), C {} } De ne variants of enum; can be unit- A , tuple- B () and struct-like C{} .
enum E { A = 1 } If variants are only unit-like, allow discriminant values, e.g., for FFI.
static X: T = T(); Global variable BK EX REF with 'static lifetime, single memory location.
const X: T = T(); De nes constant BK EX REF. Copied into a temporary when used.
let mut x: T; Like let , but allow for mutability BK EX and mutable borrow.2
Creating and accessing data structures; and some more sigilic types.
Example Explanation
S { x: y } Create struct S {} or use 'ed enum E::S {} with eld x set to y .
S (x) Create struct S (T) or use 'ed enum E::S () with eld .0 set to x .
https://cheats.rs/#printing-pdf 1/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
[S] Array type of unspeci ed length, i.e., slice. EX STD REF Can't live on stack. *
s.x Named eld access, REF might try to Deref if x not part of type S .
Example Explanation
&S Shared reference BK STD NOM REF
(space for holding any &s ).
&mut S Exclusive reference to allow mutability (also &mut [S] , &mut dyn S , ...)
&dyn T Special trait object BK reference that contains ( address , vtable ).
*const S Immutable raw pointer type BK STD REF w/o memory safety.
&s Shared borrow BK EX STD (e.g., address, len, vtable, ... of this s , like 0x1234 ).
let S { ref mut x } = s; Mutable ref binding ( let x = &mut s.x ), shorthand destructuring ↓ version.
s = *my_box; Special case for Box that can also move out Box'ed content if it isn't Copy .
&'a S Only accepts a s with an address that lives 'a or longer.
struct S<'a> {} Signals S will contain address with lifetime 'a . Creator of S decides 'a .
trait T<'a> {} Signals a S which impl T for S might contain address.
https://cheats.rs/#printing-pdf 2/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
trait T {} De ne a trait; BK EX REF common behavior others can implement.
trait T : R {} T is subtrait of supertrait REF R . Any S must impl R before it can impl T .
const fn f() {} Constant fn usable at compile time, e.g., const X: u32 = f(Y) . '18
async fn f() {} Async REF '18 function transformation, makes f return an impl Future . STD
async fn f() -> S {} Same, but make f return an impl Future<Output=S> .
fn() -> S Function pointers, BK STD REF, memory holding address of a callable.
Fn() -> S Callable Trait, BK STD (also FnMut , FnOnce ), implemented by closures, fn's ...
|x| x + x Closure without block expression; may only consist of single expression.
return || true Closures sometimes look like logical ORs (here: return a closure).
unsafe {} If you enjoy debugging segfaults Friday night; unsafe code. BK EX NOM REF
Control Flow
Control execution within a function.
Example Explanation
while x {} Loop , run while expression x is true.
REF
loop {} Loop in nitely REF until break . Can yield value with break x .
'label: loop {} Loop label EX REF, useful for ow control in nested loops.
break x Same, but make x value of the loop expression (only in actual loop ).
break 'label Exit not only this loop, but the enclosing one marked with 'label .
continue Continue expression REF to the next loop iteration of this loop.
continue 'label Same, but instead of enclosing loop marked with 'label .
return x Early return from function. More idiomatic way is to end with expression.
x.f() Call member function, requires f takes self , &self , ... as rst argument.
X::f(x) Same as x.f() . Unless impl Copy for X {} , f can only be called once.
T::f(&x) Same as x.f() if X impl T , i.e., x.f() nds methods of T if in scope.
https://cheats.rs/#printing-pdf 3/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
X::f() Call associated function, e.g., X::new() .
Organizing Code
Segment projects into smaller units and minimize dependencies.
Example Explanation
mod m {} De ne a module, BK EX REF get de nition from inside {} . ↓
use a::b; Use EX REF b directly in this scope without requiring a anymore.
use a::b as x; Bring b into scope but name x , like use std::error::Error as E .
use a::b as _; Bring b anonymously into scope, useful for traits with con icting names.
pub use a::b; Bring a::b into scope and reexport from here.
extern crate a; Declare dependency on external crate BK EX REF 🗑 ; just use a::b in '18.
extern "C" {} Declare external dependencies and ABI (e.g., "C" ) from FFI. BK EX NOM REF
extern "C" fn f() {} De ne function to be exported with ABI (e.g., "C" ) to FFI.
Example Explanation
type T = S; Create a type alias , i.e., another name for S .
BK REF
Self Type alias for implementing type REF, e.g. fn new() -> Self .
&self Same, but refers to self as borrowed, same as f(self: &Self)
&mut self Same, but mutably borrowed, same as f(self: &mut Self)
self: Box<Self> Arbitrary self type, add methods to smart pointers ( my_box.f_of_self() ).
x as u32 Primitive cast EX REF, may truncate and be a bit surprising. NOM
https://cheats.rs/#printing-pdf 4/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
m!() Macro BK STD REF invocation, also m!{} , m![] (depending on macro).
$x:meta A meta item; the things that go inside #[...] and #![...] attributes.
$x:tt A single token tree, see here for more details.
$(x)<<+ In fact separators other than , are also accepted. Here: << .
Pattern Matching
Constructs found in match or let expressions, or function parameters.
Example Explanation
match m {} Initiate pattern matching BK EX REF, then use match arms, c. next table.
let S(x) = get(); Notably, let also destructures EX similar to the table below.
let (a, ..) = abc; Ignoring 'the rest' also works.
let (.., a, b) = (1, 2); Speci c bindings take precedence over 'the rest', here a is 1 , b is 2 .
let Some(x) = get(); Won't work 🛑 if pattern can be refuted REF, use if let instead.
if let Some(x) = get() {} Branch if pattern can be assigned (e.g., enum variant), syntactic sugar. *
fn f(S { x }: S) Function parameters also work like let , here x bound to s.x of f(s) .
*
Desugars to match get() { Some(x) => {}, _ => () } .
Pattern matching arms in match expressions. Left side of these arms can also be found in let expressions.
https://cheats.rs/#printing-pdf 5/16
21/08/2020 Rust Language Cheat Sheet
S { x: 0, y: 1 } => {} Match struct with speci c values (only accepts s with s.x of 0 and s.y of 1 ).
S { x: a, y: b } => {} Match struct with any(!) values and bind s.x to a and s.y to b .
S { x, y } => {} Same, but shorthand with s.x and s.y bound as x and y respectively.
D => {} Match anything, bind D ; possibly false friend 🛑 of E::D if D not in use .
(a, 0) => {} Match tuple with any value for a and 0 for second.
[a, 0] => {} Slice pattern, REF 🔗 match array with any value for a and 0 for second.
[1, ..] => {} Match array starting with 1 , any value for rest; subslice pattern. ?
[2, .., 5] => {} Match array starting with 1 , ending with 5 .
[2, x @ .., 5] => {} Same, but also bind x to slice representing middle (c. next entry).
x @ 1..=5 => {} Bind matched to x ; pattern binding, BK EX REF here x would be 1 , 2 , ... or 5 .
E::C {x} | E::D {x} Same, but bind x if all variants have it.
S { x } if x > 10 => {} Pattern match guards, BK EX REF condition must be true as well to match.
Example Explanation
S<T> A generic BK EX type with a type parameter ( T is placeholder name here).
S<T: R> Type short hand trait bound BK EX speci cation ( R must be actual trait).
T: R, P: S Independent trait bounds (here one for T and one for P ).
T: R + 'a Same, but w. lifetime. T must ful ll R , if T has lifetimes, must outlive 'a .
T: ?Sized Opt out of a pre-de ned trait bound, here Sized . ?
T: 'a Type lifetime bound EX; if T has references, they must outlive 'a .
T: 'static Same; does esp. not mean value t will 🛑 live 'static , only that it could.
'b: 'a Lifetime 'b must live at least as long as (i.e., outlive) 'a bound.
S<T> where T: R Same as S<T: R> but more pleasant to read for longer bounds.
S<'_> Inferred anonymous lifetime; asks compiler to ' gure it out' if obvious.
trait T<X> {} A trait generic over X . Can have multiple impl T for S (one per X ).
trait T { type X; } De nes associated type BK REF X . Only one impl T for S possible.
fn f() -> impl T Existential types BK, returns an unknown-to-caller S that impl T .
https://cheats.rs/#printing-pdf 6/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
fn f(x: &impl T) Trait bound,"impl traits" BK
, somewhat similar to fn f<S:T>(x: &S) .
fn f(x: &dyn T) Marker for dynamic dispatch BK REF, f will not be monomorphized.
fn f() where Self: R; In trait T {} , make f accessible only on types known to also impl R .
fn f() where Self: R {} Esp. useful w. default methods (non d t. would need be impl'ed anyway).
trait T: for<'a> R<'a> {} Any S that impl T would also have to ful ll R for any lifetime.
Example Explanation
"..." String literal, REF UTF-8, will interpret \n as line break 0xA , ...
r#"..."# Raw string literal, UTF-8, but can also contain " . Number of # can vary.
b"..." Byte string literal; REF constructs ASCII [u8] , not a string.
br"..." , br#"..."# Raw byte string literal, ASCII [u8] , combination of the above.
Comments
No comment.
Example Explanation
// Line comment, use these to document code ow or internals.
//! Inner line doc comment, mostly used at start of le to document module.
```rust ... ``` In doc comments, include a doc test (doc code running on cargo test ).
# In doc tests, hide line from documentation ( ``` # use x::hidden; ``` ).
Miscellaneous
These sigils did not t any other category but are good to know nonetheless.
Example Explanation
! Always empty never type. 🚧 BK EX STD REF
let _ = x; Unnamed assignment is no-op, does not 🛑 move out x or preserve scope!
1_u8 Type speci er for numeric literals EX REF (also i8 , u16 , ...).
https://cheats.rs/#printing-pdf 7/16
21/08/2020 Rust Language Cheat Sheet
Common Operators
Rust supports most operators you would expect ( + , * , % , = , == ...), including overloading. STD Since they behave no di erently in Rust
we do not list them here.
Language Sugar
If something works that "shouldn't work now that you think about it", it might be due to one of these.
Name Description
Coercions NOM
'Weaken' types to match signature, e.g., &mut T to &T .
Deref NOM
Deref x: T until *x , **x , ... compatible with some target S .
Editorial Comment 💬 — The features above will make your life easier, but might hinder your understanding. If you are new to
Rust, you should consider reading about them in more detail.
Standard Library
Common One-Liners
Snippets that are common, but still easy to forget. See Rust Cookbook 🔗 for more.
Intent Snippet
Parse a number "42".parse::<u32>()?
Fix inference in ' try ' closures iter.try_for_each(|x| { Ok::<(), Error>(()) })?;
Traits
Traits de ne common behavior. If S implements trait T , you know S can behave as prescribed by T . Below is an overview of traits
that may be more tricky.
Thread Safety
https://cheats.rs/#printing-pdf 8/16
21/08/2020 Rust Language Cheat Sheet
Examples Send *
!Send
*
An instance t where T: Send can be moved to another thread, a T: Sync means &t can be moved to another thread.
1
If T is Sync .
2
If T is Send .
A type T is Sized STD if at compile time it is known how many bytes it occupies, u8 and &[u8] are,
[u8] isn't.
Being Sized means impl Sized for T {} holds. Happens automatically and cannot be user
impl'ed.
Types not Sized are called dynamically sized types BK NOM REF (DSTs), sometimes unsized.
Types without data are called zero sized types NOM (ZSTs), do not occupy space.
🚥 Iterators
Basics
The Iterator
For Loops
*
If it looks as if it doesn't consume c that's because type was Copy . For example, if you call (&c).into_iter() it will invoke
.into_iter() on &c (which will consume the reference and turn it into an Iterator), but c remains untouched.
String Conversions
If you want a string of type ...
https://cheats.rs/#printing-pdf 9/16
21/08/2020 Rust Language Cheat Sheet
String CString OsString PathBuf Vec<u8> &str &CStr &OsStr &Path &[u8] Other
CString x.into_string()?
OsString x.to_str()?.to_string()
PathBuf x.to_str()?.to_string()
Vec<u8> 1 String::from_utf8(x)?
i
&str x.to_string()
&CStr x.to_str()?.to_string()
&OsStr x.to_str()?.to_string()
&Path x.to_str()?.to_string()
&[u8] 1 String::from_utf8_lossy(x).to_string()
i
Short form x.into() possible if type can be inferred.
r
Short form x.as_ref() possible if type can be inferred.
1
You should, or must if call is unsafe , ensure raw data comes with a valid representation for the string type (e.g., UTF-8 data for a String ).
2
Only on some platforms std::os::<your_os>::ffi::OsStrExt exists with helper methods to get a raw &[u8] representation of the underlying OsStr . Use the rest of
the table to go from there, e.g.:
use std::os::unix::ffi::OsStrExt;
let bytes: &[u8] = my_os_str.as_bytes();
CString::new(bytes)?
3
The c_char must have come from a previous CString . If it comes from FFI see &CStr instead.
String Formatting
Formatting applies to print! , eprint! , write! (and their - ln siblings like println! ). Each format argument is either empty {} ,
{argument} , or follows a basic syntax:
{ [argument] ':' [[fill] align] [sign] ['#'] [width [$]] ['.' precision [$]] [type] }
Element Meaning
argument Number ( 0 , 1 , ...) or argument name, e.g., print!("{x}", x = 3) .
fill The character to ll empty spaces with (e.g., 0 ), if width is speci ed.
width Minimum width (≥ 0), padding with fill (default to space). If starts with 0 , zero-padded.
$ Interpret width or precision as argument identi er instead to allow for dynamic formatting.
type Debug ( ? ) formatting, hex ( x ), binary ( b ), octal ( o ), pointer ( p ), exp ( e ) ... see more.
Example Explanation
{:?} Print the next argument using Debug.
{val:^2$} Center the val named argument, width speci ed by the 3rd argument.
https://cheats.rs/#printing-pdf 10/16
21/08/2020 Rust Language Cheat Sheet
Example Explanation
{:<10.3} Left align with width 10 and a precision of 3.
{val:#x} Format val argument as hex, with a leading 0x (alternate format for x ).
Tooling
Project Anatomy
Basic project layout, and common les and folders, as used by cargo . ↓
Entry Code
📁 benches/ Benchmarks for your crate, run via cargo bench , requires nightly by default. * 🚧
📁 examples/ Examples how to use your crate, they see your crate like external user would.
my_example.rs Individual examples are run like cargo run --example my_example .
build.rs Pre-build script 🔗, e.g., when compiling C / FFI, needs to be speci ed in Cargo.toml .
main.rs Default entry point for applications, this is what cargo run uses.
lib.rs Default entry point for libraries. This is where lookup for my_crate::f() starts.
📁 tests/ Integration tests go here, invoked via cargo test . Unit tests often stay in src/ le.
.clippy.toml Special con guration for certain clippy lints, utilized via cargo clippy
Cargo.lock Dependency details for reproducible builds, recommended to git for apps, not for libs.
* On stable consider Criterion.
Modules BK EX REF and source les work as follows:
Module tree needs to be explicitly de ned, is not implicitly built from le system tree. 🔗
Module tree root equals library, app, ... entry point (e.g., lib.rs ).
A mod m {} de nes module in- le, while mod m; will read m.rs or m/mod.rs .
Path of .rs based on nesting, e.g., mod a { mod b { mod c; }}} is either a/b/c.rs or a/b/c/mod.rs .
Files not pathed from module tree root via some mod m; won't be touched by compiler! 🛑
Cargo
Commands and tools that are good to know.
Command Description
cargo init Create a new project for the latest edition.
cargo b uild Build the project in debug mode ( --release for all optimization).
cargo run --bin b Run binary b . Uni es features with other dependents (can be confusing).
cargo run -p w Run main of sub-workspace w . Treats features more as you would expect.
https://cheats.rs/#printing-pdf 11/16
21/08/2020 Rust Language Cheat Sheet
Command Description
cargo doc --open Locally generate documentation for your code and dependencies.
cargo rustc -- -Zunpretty=X Show more desugared Rust code, in particular with X being:
cargo +{nightly, stable} ... Runs command with given toolchain, e.g., for 'nightly only' tools.
rustup doc Open o ine Rust documentation (incl. the books), good on a plane!
A command like cargo b uild means you can either type cargo build or just cargo b .
These are optional rustup components. Install them with rustup component add [tool] .
Tool Description
cargo clippy Additional (lints) catching common API misuses and unidiomatic code. 🔗
Cross Compilation
🔘 Check target is supported.
Get from target vendor (Google, Apple, ...), might not be available on all hosts (e.g., no iOS toolchain on Windows).
[target.aarch64-linux-android]
linker = "[PATH_TO_TOOLCHAIN]/aarch64-linux-android/bin/aarch64-linux-android-clang"
or
[target.aarch64-linux-android]
linker = "C:/[PATH_TO_TOOLCHAIN]/prebuilt/windows-x86_64/bin/aarch64-linux-android21-clang.cmd"
🔘 Set environment variables (optional, wait until compiler complains before setting):
set CC=C:\[PATH_TO_TOOLCHAIN]\prebuilt\windows-x86_64\bin\aarch64-linux-android21-clang.cmd
set AR=C:\[PATH_TO_TOOLCHAIN]\prebuilt\windows-x86_64\bin\aarch64-linux-android-ar.exe
...
Whether you set them depends on how compiler complains, not necessarily all are needed.
Some platforms / con gurations can be extremely sensitive how paths are speci ed (e.g., \ vs / ) and quoted.
Coding Guides
https://cheats.rs/#printing-pdf 12/16
21/08/2020 Rust Language Cheat Sheet
Idiomatic Rust
If you are used to programming Java or C, consider these.
Idiom Code
Think in Expressions x = if x { a } else { b };
x = loop { break 5 };
names.iter().filter(|x| x.starts_with("A"))
get_option()?.run()?
Split Implementations Generic types S<T> can have a separate impl per T .
Rust doesn't have OO, but with separate impl you can get specialization.
Unsafe Avoid unsafe {} , often safer, faster solution without it. Exception: FFI.
Implement Traits #[derive(Debug, Copy, ...)] and custom impl where needed.
Add doc tests BK ( ``` my_api::f() ``` ) to ensure docs match code.
Documentation Annotate your APIs with doc comments that can show up on docs.rs.
Don't forget to include a summary sentence and the Examples heading.
If applicable: Panics, Errors, Safety, Abort and Unde ned Behavior.
🔥 We highly recommend you also follow the API Guidelines (Checklist) for any shared project! 🔥
Async-Await 101
If you are familiar with async / await in C# or TypeScript, here are some things to keep in mind:
Construct Explanation
async Anything declared async always returns an impl Future<Output=_> . STD
async fn f() {} Function f returns an impl Future<Output=()> .
Function f returns an impl Future<Output=S> .
async fn f() -> S {}
Likewise, does not execute the { g() } block; produces state machine.
sm = async { g() };
https://cheats.rs/#printing-pdf 13/16
21/08/2020 Rust Language Cheat Sheet
Construct Explanation
Outside an async {} , schedules sm to actually run. Would execute g() . 3
runtime.block_on(sm);
4
4
Rust doesn't come with runtime, need external crate instead, e.g., async-std or tokio 0.2+. Also, more helpers in futures crate.
Closures in APIs
There is a subtrait relationship Fn : FnMut : FnOnce . That means a closure that implements Fn STD
also implements FnMut and FnOnce .
Likewise a closure that implements FnMut STD
also implements FnOnce . STD
Notice how asking for a Fn closure as a function is most restrictive for the caller; but having a Fn closure as a caller is most compatible with any function.
From the perspective of someone de ning a closure:
|| { &s; } FnOnce , FnMut , Fn May not mutate state; but can share and reuse s .
*
Rust prefers capturing by reference (resulting in the most "compatible" Fn closures from a caller perspective), but can be forced to
capture its environment by copy or move via the move || {} syntax.
That gives the following advantages and disadvantages:
F: FnMut Allows g() to change caller state. Caller may not reuse captures during g() .
Unsafe Code
Code marked unsafe has special permissions, e.g., to deref raw pointers, or invoke other unsafe
functions.
https://cheats.rs/#printing-pdf 14/16
21/08/2020 Rust Language Cheat Sheet
Along come special promises the author must uphold to the compiler, and the compiler will
trust you.
By itself unsafe code is not bad, but dangerous, and needed for FFI or exotic data structures.
API Stability
When updating an API, these changes can break client code, compare RFC 1105. Major changes (🔴) are de nitely breaking, while
minor changes ( ) might be breaking:
Crates
🔴 Making a crate that previously compiled for stable require nightly.
Altering use of Cargo features (e.g., adding or removing features).
Modules
🔴 Renaming / moving / removing any public items.
Adding new public items, as this might break code that does use your_crate::* .
Structs
🔴 Adding private eld when all current elds public.
🔴 Adding public eld when no private eld exists.
Adding or removing private elds when at least one already exists (before and after the change).
Going from a tuple struct with all private elds (with at least one eld) to a normal struct, or vice versa.
Enums
🔴 Adding new variants.
🔴 Adding new elds to a variant.
Traits
🔴 Adding a non-defaulted item, breaks all existing impl T for S {} .
🔴 Any non-trivial change to item signatures, will a ect either consumers or implementors.
Adding a defaulted item; might cause dispatch ambiguity with other existing trait.
Adding a defaulted type parameter.
Traits
🔴 Implementing any "fundamental" trait, as not implementing a fundamental trait already was a promise.
Implementing any non-fundamental trait; might also cause dispatch ambiguity.
https://cheats.rs/#printing-pdf 15/16
21/08/2020 Rust Language Cheat Sheet
Inherent Implementations
Adding any inherent items; might cause clients to prefer that over trait fn and produce compile error.
Signatures in Type De nitions
🔴 Tightening bounds (e.g., <T> to <T: Clone> ).
Loosening bounds.
Adding defaulted type parameters.
Generalizing to generics.
Signatures in Functions
🔴 Adding / removing arguments.
Introducing a new type parameter.
Generalizing to generics.
Behavioral Changes
🔴/ Changing semantics might not cause compiler errors, but might make clients do wrong thing.
Ralf Biedert, 2020 – cheats.rs
https://cheats.rs/#printing-pdf 16/16