Rust Language Quick Reference Guide
Rust Language Quick Reference Guide
rs/
|
Needsownership
Share
Same, but
to beallow
heldsharing
struct
T: Sized S;
S ; of in Arc
T in to
between
same
be shared
thread.
threads
between
Needs
IF contained
nested Cell
T itself
or
threads,
RefCellisalways
Send and
to allow and
Sync
Send . SyncIs. Consider
mutation. neither Send
using
nor Sync .
parking_lot instead (faster, no heap usage).
Contains
Where *Dropclickable
Drop::
::drop
drop( links
() , * to
Trait
Trait:: The
::f
f Book
() , ... are BK, Rust by Example EX, Std Docs STD, Nomicon NOM, Reference REF. Other symbols used: largely
deprecated
pointers to their � , has a minimum
respective impl for T .edition '18
, is work in progress �, or bad �.
Data Structures
Data types and memory locations de�ned via keywords.
Example Explanation
struct S (T); De�ne "tupled" struct with numbered �eld .0 of type T .
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 and mutable borrow. 2
Creating and accessing data structures; and some more sigilic types.
Example Explanation
S (x) Create struct S (T) or use 'ed enum E::S () with �eld .0 set to x .
[S] Array type of unspeci�ed length, i.e., slice. STD EX REF Can't live on stack. *
1 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Example Explanation
[x, y] Array instance with given elements x and y .
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 ).
&dyn S Special trait object BK reference that contains ( address , vtable ).
&mut S Exclusive reference to allow mutability (also &mut [S] , &mut dyn S , ...)
*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 ).
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.
S<'a> Signals S will contain address with lifetime 'a . Creator of S decides 'a .
Example Explanation
const fn f() {} Constant fn usable at compile time, e.g., const X: u32 = f(Y) . '18
2 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Example Explanation
async fn f() {} Async '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 don't confuse with trait Fn.
return || true Closures may sometimes look like logical ORs (here: return a closure).
unsafe {} If you need to crash your code in production; unsafe code. BK EX NOM REF
Control Flow
Control execution within a function.
Example Explanation
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 .
x.await Only works inside async . Yield �ow until Future or Stream ? x ready. '18
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).
Organizing Code
Segment projects into smaller units and minimize dependencies.
Example Explanation
use a::b; Use EX REF b directly in this scope without requiring a anymore.
3 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Example Explanation
use a::{b, c}; Same, but bring b and c into scope.
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
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
Example Explanation
$x:ty Macro capture, also $x:expr , $x:ty , $x:path , ... see next table.
$(x)<<+ In fact separators other than , are also accepted. Here: << .
4 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
$x:meta A meta item; the things that go inside #[...] and #![...] attributes.
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 pattern matches similar to the table below.
let (a, ..) = abc; Ignoring 'the rest' also works.
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 actually be assigned (e.g., enum variant).
fn f(S { x }: S) Function parameters also work like let , here x bound to s.x of f(s) .
Pattern matching arms in match expressions. The left side of these arms can also be found in let expressions.
Example Explanation
S { x, y } => {} Match struct with any values, bind respective �elds as variables x and y .
D => {} Match anything, bind D ; possibly false friend � of E::D if D not in use .
[a, 0] => {} Match array with any value for a and 0 for second.
(a, 0) => {} Match tuple with any value for a and 0 for second.
E::C {x} | E::D {x} Same, but bind x if all variants have it.
Example Explanation
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 .
5 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Example Explanation
T: 'a Type lifetime bound EX; if T has references, they must outlive 'a .
'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.
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 .
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 a trait T {} , mark f as accessible only on types that also impl R .
Example Explanation
"..." String literal, REF UTF-8, will escape \n to line break 0xA , ...
r#"..."# , etc. Raw string literal, UTF-8, but can also contain " .
b"..." Byte string literal; REF constructs ASCII [u8] , not a string.
br"..." , br#"..."# , etc. Raw byte string literal, ASCII [u8] , combination of the above.
'�
�' Character literal, REF �xed 4 byte unicode 'char'. STD
Comments
No comment.
Example Explanation
//! Inner line doc comment BK EX REF for auto generated documentation.
```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
6 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Example Explanation
1_234_567 Numeric separator for visual clarity.
1_u8 Type speci�er for numeric literals EX REF (also i8 , u16 , ...).
Common Operators
Rust supports all common operators you would expect to �nd in a language ( + , * , % , = , == ...). Since they behave no di�erently in Rust we do not list
them here. For some of them Rust also supports operator overloading. STD
Basic Types
Memory representations are depicted for little-endian architectures (e.g., x86-64).
u8 255
u16 65_535
u32 4_294_967_295
u64 18_446_744_073_709_551_615
u128 340_282_366_920_938_463_463_374_607_431_768_211_455
*
i8 , i16 , ... values range from -max/2 to max/2 , rounded towards negative in�nity.
f32 f64
Float types are slightly more complicated and follow IEEE 754-2008.
7 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
char str
Any UTF-8 char. Rarely seen alone, but as &'a str instead.
Notice how:
char is always 4 bytes and only holds a single Unicode scalar value (thus possibly wasting space),
str is a byte-array of unknown length guaranteed to hold UTF-8 code points (but harder to index).
Custom Types
Basic types that can be de�ned by the user. The compiler might add additional padding under certain conditions.
T: !Sized (A, B
B,
, C
C)
) struct S { b:
b: B
B,
, c:
c: C }
T ←T→ A B C B C
[T; n
n]
] [T]
These sum types hold a value of either one of their sub types:
enum E { A
A,
, B
B,
, C } union { ... }
Tag A A
or and
Tag B B
or and
Tag C C
Rust also has a number of special reference types that encode more than just an address, see below. The respective &mut version is identical and
omitted:
8 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
ptr 4/8 len 4/8 ptr 4/8 len 4/8 ptr 4/8 ptr 4/8
| | |
Box is Rust's type for heap allocation that also comes in a number of special variants:
Box<
Box<T> Box<
Box<[T]> Box<
Box<dyn Trait>
Trait>
ptr 4/8 ptr 4/8 len 4/8 ptr 4/8 ptr 4/8
| | | |
Compare above.
UnsafeCell<
UnsafeCell<T> Cell<
Cell<T> RefCell<
RefCell<T> AtomicUsize Option<
Option<T>
Result<
Result<T, E
E>
>
Tag E
or
Tag T
These dynamic collections grow when needed and are backed by the heap:
Vec<
Vec<T> String
ptr 4/8 capacity 4/8 len 4/8 ptr 4/8 capacity 4/8 len 4/8
| |
Shared ownership of memory and resources. If the type does not contain a Cell for T , these are often combined with one of the Cell types above
to allow shared de-facto mutability.
9 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Rc<
Rc<T> Arc<
Arc<T>
Mutex<T> / RwLock<
Mutex< RwLock<T>
Guides
Project Anatomy
Basic project layout, and common �les and folders, as used by Rust tooling.
Idiom Code
benches/ Benchmarks for your crate, run via cargo bench , only useful in nightly. �
examples/ Examples how to use your crate, run via 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.
Cargo.lock Dependency details for reproducible builds, recommended to git for apps, not for libs.
An minimal library entry point with functions and modules looks like this:
pub fn f() {} // Is a public item in root, so it's accessible from the outside.
mod m {
pub fn g() {} // No public path (`m` not public) from root, so `g`
} // is not accessible from the outside of the crate.
For binaries (not depicted), function fn main() {} is the entry point. Unit tests (not depicted), usually reside in a #[cfg(test)] mod test { } next to
their code. Integration tests and benchmarks, in their basic, form look like this:
#[test]
fn my_sample() {
assert_eq!(my_crate::f(), 123); // Integration tests (and benchmarks) 'depend' to the crate like
} // a 3rd party would. Hence, they only see public items.
10 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
extern crate test; // Even in '18 this is needed ... for reasons.
// Normally you don't need this in '18 code.
#[bench]
fn my_algo(b: &mut Bencher) {
b.iter(|| black_box(my_crate::f())); // `black_box` prevents `f` from being optimized away.
}
Idiomatic Rust
If you are used to programming Java or C, consider these.
Idiom Code
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.
� 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
11 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
Construct Explanation
let sm = f(); Calling f() that is async will not execute f , but produce state machine sm . 1
sm = async { g() }; Likewise, does not execute the { g() } block; produces state machine.
runtime.block_on(sm); 2
Outside an async {} , schedules sm to actually run. Would execute g() .
sm.await Inside an async {} , run sm until complete. Yield to runtime if sm not ready.
1
Technically async transforms the following code into an anonymous, compiler-generated state machine type, and f() instantiates that machine. The state machine always impl Future
, possibly Send & co, depending on types you used inside async . State machine driven by worker thread invoking Future::poll() via runtime directly, or parent .await indirectly.
2
Right now Rust doesn't come with its own runtime. Use external crate instead, such as async-std or tokio 0.2+. Also, Futures in Rust are an MPV. There is much more utility stu� in the
futures crate.
At each x.await , state machine passes control to subordinate state machine x . At some point a low-level state machine invoked via .await might
not be ready. In that the case worker thread returns all the way up to runtime so it can drive another Future. Some time later the runtime:
This leads to the following considerations when writing code inside an async construct:
Constructs 1 Explanation
set_TL(a); x.await; TL(); De�nitely bad �, await may return from other thread, thread local invalid.
s.no(); x.await; s.go(); Maybe bad �, await will not return if Future dropped while waiting. 2
Rc::new(); x.await; rc(); Non- Send types prevent impl Future from being Send ; less compatible.
1 Here we assume s is any non-local that could temporarily be put into an invalid state; TL is any thread local storage, and that the async {} containing the code is written without
assuming executor speci�cs.
2
Since Drop is run in any case when Future is dropped, consider using drop guard that cleans up / �xes application state if it has to be left in bad condition across .await points.
Closures
There is a subtrait relationship Fn : FnMut : FnOnce . That means, a closure that implements Fn , also implements FnMut and FnOnce . Likewise, a
closure that implements FnMut , also implements FnOnce .
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.
|| { &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.
12 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
F: FnOnce Easy to satisfy as caller. Single use only, g() may call f() just once.
F: FnMut Allows g() to change caller state. Caller may not reuse captures during g() .
let s: S = S(0) A location that is S -sized, named s , and contains the value S(0) .
To explicitly talk about a location that can hold such a location we do &S .
&'a S A &S is a location that can hold (at least) an address, called reference.
Any address stored must be proven to exist for at least (outlive) duration 'a .
In other words, the &S part sets bounds for what any address here must contain.
While the &'a part sets bounds for how long any such address must at least live.
The lifetime our containing location is unrelated, but naturally always shorter.
&S Sometimes 'a might be elided (or can't be speci�ed) but it still exists.
&s This will produce the actual address of location s , called 'borrow'.
Borrowing of s stops once last &s is last used, not when &s dropped.
A &mut will allow the owner of the borrow (address) to change s content.
S<'a> {} Signals that S will contain* at least one address (i.e., reference).
f<'a>(x: &'a T) Signals this function will accept an address (i.e., reference).
-> &'a S ... and that it returns one.
'a will be picked so that it satis�es input and output at call site.
13 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
<'a, 'b: 'a> The lifetimes declared in S<> and f<> can also have bounds.
The <'a, 'b> part means the type will handle at least 2 addresses.
The 'b: 'a part is a lifetime bound, and means 'b must outlive 'a .
Invisible 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 .
Prelude STD
Automatic import of basic types.
Lifetime Elision BK NOM REF Automatically annotate f(x: &T) to f<'a>(x: &'a T) .
Formatting Strings
Formatting applies to print! , eprint! , write! (and their - ln siblings like println! ). The format! macro can create a formatted String .
{[argument][':'[[fill]align][sign]['#']['0'][width]['.' precision][type]]}
The full grammar is speci�ed in the std::fmt documentation, but here are some commonly used �ags:
Element Meaning
align Left ( < ), center ( ^ ), or right ( > ) , if width is speci�ed, �lls with fill .
type Debug ( ? ), hex ( x ), binary ( b ), or octal ( o ) (there are more, using Traits).
Note that width and precision can use other arguments as their values, allowing for dynamic sizing of �elds.
Example Explanation
{val:^2$} Center the val named argument, width speci�ed by the 3rd argument.
{val:#x} Format val argument as hex, with a leading 0x (alternate format for x ).
Tooling
Some commands and tools that are good to know.
Command Description
14 of 15 12/23/19, 9:55 PM
Rust Language Cheat Sheet https://cheats.rs/
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 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 docs 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. �
15 of 15 12/23/19, 9:55 PM