Rust Language Cheat Sheet
Rust Language Cheat Sheet
rs/
Data Structures
Define data types and memory locations, and use them.
Example Explanation
enum E { A, C {} } Define 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.
const X: T = T(); Define inlineable constant, BK EX REF. Inlined values are mutable!!!
let mut x: T; Like let , but allow for mutability and mutable borrow.
x = y Same, but also invalidate y if T not Copy . Compiler might optimize.
Example Explanation
S (x) Create struct S (T) or use 'ed enum E::S () with field .0 set to x .
[S] Array of unspecified length, i.e., slice. STD EX REF Can't live on stack.
Example Explanation
[x; n] Array with n copies of x . REF
Example Explanation
&[S] Special slice reference that contains address and length (like &str ).
&mut S Exclusive reference to allow mutability (also &mut [S] , &mut dyn S , ...)
*mut S Mutable raw pointer type, like &mut S but w/o compile safety.
&s Shared borrow BK EX STD (on low level, address of this s , like 0x1234 ).
&'a S Place for an address of a S . Only accepts addr. living 'a or longer.
S<'a> Signals S will contain address with lifetime 'a . Creator of S decides 'a .
Sigil Explanation
Sigil Explanation
fn f(&self) {} Define a method as part of an impl .
const fn f() {} Constant fn for compile time compilations, e.g., const X: u32 = f(Y) . '18
fn() -> T Function pointers, BK STD REF don't confuse with trait Fn.
return || true Closures may sometimes look like logical ORs (here: return a closure).
x.f() Call member function, requires f takes self , &self , ... as first 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() finds methods of T if in scope).
Control Flow
Control execution within a function.
Sigil Explanation
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 'label Same, but instead of enclosing loop marked with 'label .
return x Early return from function. More idiomatic way is to end with expression.
Organizing Code
Segment projects into smaller units and minimize dependencies.
Sigil Explanation
'18
crate::x Search x relative to crate root.
Sigil Explanation
self::x Search x relative to current module.
use a::b; Use EX REF b directly in this scope without requiring a anymore.
pub use a::b; Bring a::b into scope and reexport from here.
extern crate x ; Declare dependency on external crate BK EX REF � ; just use x::f in '18.
Sigil Explanation
&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() ).
S as T Disambiguate BK REF
type S as trait T .
Code Generation
Constructs expanded before the actual compilation happens.
Example Explanation
m!() Macro BK STD REF invocation, also m!{} , m![] (depending on macro).
$(x)<<+ In fact separators other than , are also accepted. Here: << .
Pattern Matching
These constructs are found in match or let expressions.
Example Explanation
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.
Example Explanation
let Some(x) = Some(5) Notably, let also pattern matches similar to the table above.
let (a, ..) = abc Ignoring 'the rest' also works.
let Some(x) = get() ⚡ Will not work if pattern can be 'refuted', use if let instead.
fn f(S { x }: S) Function parameters also work like let , here x bound to s.x of f(s) .
Example Explanation
'b: 'a Lifetime 'b must live at least as long as (i.e., outlives) 'a bound.
S<T> where T: R Same as S<T: R> but easier for longer bounds.
trait T<X> {} A trait generic over X . Can have multiple impl T for S (one per X ).
Example Explanation
impl<T> S<T> {} Implement functionality for any T in S<T> .
fn f(x: &impl T) Trait bound,"impl traits" BK, somewhat similar to fn f<S:T>(x: &S) .
Example Explanation
r#"..."# , etc. Raw string literal, but can also contain " .
br"..." , br#"..."# , etc. Raw byte string literal, combination of the above.
'�
�' Character literal REF
, can contain unicode.
Comments
No comment.
Example Explanation
// Line comment.
Miscellaneous
These sigils did not fit any other category but are good to know nonetheless.
Example Explanation
x; Statement REF
terminator, c. expressions EX REF
Common Operators
Rust supports all common operators you would expect to find in a language ( + , * , % , = , == ...). Since they behave no differently in Rust we do
not list them here. For some of them Rust also support operator overloading. STD
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
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(x: &'a T) .
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; can reuse same vars.
* 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.
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() .
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"))
Idiom Code
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 Guideline Checklist if you are writing a shared project �
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 .
Any address stored must live at least for (outlive) duration 'a .
Also, this &S must be stopped being used before 'a ends.
&S Sometimes 'a might be elided (or can't be specified) 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.
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 satisfies input and output at call site.
So while result address with 'a is used, input address with 'a is locked.
Tooling
Some commands and tools that are good to know.
Command Description
cargo b uild Build the project in debug mode ( --release for all optimization).
cargo rustc -- -Zunpretty=X Show more desugared Rust code, in particular with X being:
A command like cargo b uild means you can either type cargo build or just cargo b .
These are 3rd party tools and need to be installed with cargo install cargo-[tool] first. They often require unstable and are subject to
break.
Command Description