Variable assignment

Code Description
let n = 5; Assign the value, 5, to n. The type of n is deduced.
let n : i32 = 5; Assign the value, 5, to n. n is an i32.
let n; Create a placeholder variable named n. We may assign to it (once) later.
let mut n = 5; Assign the value, 5, to n. n is mutable and may be changed later.
let n = i == 5; Assign the result of the expression, i==5 (true or false), to n. The type of n is deduced.
x = y;. Move y’s value into x (you can no longer use y), unless y is a copyable type. If its type implements [derive(Copy)], a copy is made and y remains usable.

Structures

Code Description
struct S { x:i32 } Create a structure containing a field named x of type i32. Access as s.x.
struct S (i32); Create a tuple structure containing an i32. Access as s.0.
struct S; Create a unit structure that optimizes out of our code.

Enumerations

Code Description
enum E { A, B } Define an enumeration type with the options, A and B.
enum E { A(i32), B } Define an enumeration type with A and B. A contains an i32.

Control flow

Code Description
while x { ... } Run the enclosed code until x evaluates to true.
loop { break; } Run the enclosed code until break; is called.
for i in 0..4 {...} Run the enclosed code with x equal to zero, one, two, and three. Ranges are inclusive.
for i in 0..=4 {...} Run the enclosed code with x equal to zero, one, two, three, and four. The range is exclusive.
for i in iter {...} Run code for each member of an iterator.
iter.for_each(|n|...) The same as for i in iter(); runs a closure on each element.
if x {...} else {...} If x is true, run the first code block. Otherwise, run the second.

Functions

Code Description
fn my_func() {...} Declare my_func with no parameters or return type.
fn my_func(i:i32) {..} Declare my_func with i, an i32 parameter.
fn n2(n:i32) -> i32 { n*2 } Declare n2, taking an i32 parameter and returning n*2.
|| { ... } Create a closure with no parameters.
|| 3 Create a closure with no parameters that returns 3.
|a| a*3 Create a closure that accepts a parameter named a and returns a*3.

Member/associated functions

Code Description
impl MyStruct { Functions in this block are associated with MyStruct.
fn assoc() {...} Associated function. Call as MyStruct::assoc()
fn member(&self) {...} Member function. Call as my_instance.member()
fn mem_mut(&mut self) {...} Mutable member function. Call as my_instance.member_mut(). It can change the structure-instances values.
impl Trait for MyStruct {...} Define trait member functions for MyStruct.

Matching enumerations (including result and option types)

Code Description
match e { Match on the value of e.
MyEnum::A => do_it(), For entry A, call do_it().
MyEnum::B => do_it(n), Extract member variable called n.
_ => do_something_else() } _ represents the default if nothing else matched.

Optional variables

Code Description
option.unwrap() Unwrap an optional variable, Panic/crash if the option is empty.
option.expect("Fail") Unwrap an optional variable, crash with a message if it is empty.
option.unwrap_or(3) Unwrap an optional variable, substitute 3 if the option is empty.
if let Some(option) = option { ... } Use if let to extract an option content and make it available as option if the option has a value.

Result variables

Code Description
result.unwrap() Unwrap a result variable. Panic/crash if the result is an error.
result.expect("Fail") Unwrap a result variable, crash with a message if it’s an error.
result.unwrap_or(3) Unwrap a result or substitute 3 if an error occurred.
if let Ok(result) = result { ... } Use if let to extract a result.
function_that_might_fail()? Functions that return a Result can use the ? short hand to unwrap.

Tuples & destructuring

Code Description
let i = (1, 2); Assign 1 and 2 to members 0 and 1 of tuple, i.
let (i, j) = (1, 2); Destructure i and j from the tuple, (1, 2).
i.0 Access tuple i’s first member.

Modules and imports

Code Description
mod m Reference the module, m. Look for m.rs or m/mod.rs file.
mod m { ... } Declare a module inline. Available as m::x in scope.
use m::*; Import all members of module m for use in the current scope.
use m::a; Import a from module m for use in current scope.

Iterator chains

Code Description
iter An iterator. iter() from collections, any function that returns an iterator
..for_each(|n| ... ) Run the enclosed closure on all members of the iterator.
.collect::<T>() Collect the iterator into a new collection of type, T.
.count() Count the members of the iterator.
.filter(|n| ...) Filter the iterator, retaining only entries for whom the closure returns true.
.filter_map(|n| ...) Filter the iterator, returning the first entry for whom the closure returns Some(x). Return None to ignore the entry.
.find(|n| ...) Find an entry in the iterator. Return None if no match.
.fold(|acc, x| ...) Accumulate into acc for all entries in an iterator.
.map(|n| ...) Transform members of an iterator into the closure result.
.max() Find the highest value in an iterator (numeric entries only).
.max_by(|n| ...) Find the highest value in an iterator, determined by the closure.
.min() Find the lowest value in an iterator (numeric entries only).
.min_by(|n| ...) Find the lowest value in an iterator, determined by the closure.
.nth(n) Return the iterator entry at position n.
.product() Multiply all elements (numeric entries only) of the iterator.
.rev() Reverse the order of the iterator.
.skip(n) Skip the next n entries in the iterator.
.sum() Add all the iterator entries together (numeric entries only).
.zip(other_it) Merge with another iterator, placing merged entries together in an A, B, A, B pattern.

Get hands-on with 1200+ tech skills courses.