Rust Cheat Sheet
1. Variables and Constants
Variables are immutable by default. Scope is defined by curly braces {}.
| Syntax | Type | Description |
|---|---|---|
let x = 5; |
Immutable | Binding that cannot be reassigned. |
let mut x = 5; |
Mutable | Binding that allows reassignment. |
const VAL: u32 = 10; |
Constant | Evaluated at compile-time. Must have explicit type. |
let x = 1; let x = "a"; |
Shadowing | Re-declaring a variable in the same scope. |
2. Primitive Types
Scalar Types
- Integers:
i8,i16,i32,i64,i128,isize(Signed) /u8..usize(Unsigned). - Floats:
f32,f64. - Boolean:
bool(true,false). - Character:
char(4-byte Unicode scalar).
Compound Types
- Tuple:
let t: (i32, f64) = (500, 6.4);Access viat.0,t.1. - Array:
let a: [i32; 3] = [1, 2, 3];Fixed size, stack-allocated.
3. Ownership and Borrowing
Rust manages memory via ownership rules enforced at compile-time.
Core Rules
- Each value has a variable called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
Reference Rules
| Syntax | Name | Rules |
|---|---|---|
&T |
Shared Reference | Read-only. Multiple shared references allowed. |
&mut T |
Mutable Reference | Read/Write. Only one mutable reference allowed in a scope. |
Conflict Rule: You cannot have a mutable reference while any shared references to the same value exist.
4. Strings
Rust distinguishes between owned strings and string slices.
| Type | Name | Location | Description |
|---|---|---|---|
String |
String | Heap | Growable, UTF-8 encoded. |
&str |
String Slice | Reference | Pointer to a sequence of UTF-8 bytes (stack or heap). |
5. Control Flow
Expressions
Almost all blocks in Rust are expressions and return the last value.
let x = if condition { 1 } else { 2 };
Pattern Matching
Must be exhaustive (all possible values must be handled).
match value {
1 => action_one(),
2..=5 => action_range(),
_ => default_action(), // Catch-all
}
Conditionals & Loops
if let Some(x) = opt { ... }: Executes block only if pattern matches.let Some(x) = opt else { return; };: (Let-else) Guards scope; must diverge (return/break).loop { ... }: Infinite loop. Can return values viabreak value;.while let,for x in collection.
6. Custom Structures
Structs and Enums
struct Point { x: f64, y: f64 } // Named fields
struct Color(i32, i32, i32); // Tuple struct
struct Unit; // Unit struct (no data)
enum Message {
Quit, // No data
Move { x: i32, y: i32 }, // Anonymous struct
Write(String), // Tuple data
}
Implementation
impl Point {
fn new(x: f64, y: f64) -> Self { Self { x, y } } // Static method
fn distance(&self) -> f64 { ... } // Method (shared borrow)
fn reset(&mut self) { self.x = 0.0; } // Method (mutable borrow)
}
7. Error Handling
Rust uses the type system for errors rather than exceptions.
| Type | Variants | Purpose |
|---|---|---|
Option<T> |
Some(T), None |
Represents a value that may be absent. |
Result<T, E> |
Ok(T), Err(E) |
Represents success or failure. |
Propagation
?: The “try” operator. UnwrapsOkor returnsErrto the caller immediately..unwrap(): Panics if the value isNoneorErr..expect("msg"): Panics with a custom message.
8. Functions and Closures
// Function
fn add(a: i32, b: i32) -> i32 { a + b }
// Closure (Anonymous function)
let sum = |a, b| a + b;
// Async function (Returns a Future)
async fn fetch() -> Result<(), Error> { ... }
9. Common Cargo Commands
| Command | Action |
|---|---|
cargo new <name> |
Create a new project. |
cargo check |
Verify code compiles (skips binary generation). |
cargo build --release |
Compile with optimizations. |
cargo clippy |
Run linter for idiomatic improvements. |
cargo fmt |
Format code to standard style. |
10. Memory Layout (Technical Reference)
- Stack: LIFO, fixed size, fast allocation. Used for primitives and references.
- Heap: Dynamic size, slower allocation. Used for
Vec,String,Box. - Static: Fixed memory location, lives for program duration.