Rust Cheat Sheet

Get a brief introduction to Rust's basics.

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

...