Rust Cheatsheet
Quick reference for essential Rust syntax and patterns
📋 What is a Rust Cheatsheet?
A Rust cheatsheet is a quick reference guide containing essential syntax, common patterns, and frequently used code snippets. Perfect for beginners learning Rust fundamentals and experienced developers needing quick reminders.
// Quick example - variables and functions
fn main() {
let name = "Rust";
println!("Hello, {}!", name);
}
Output:
Hello, Rust!
Quick Reference Categories
Variables & Types
Basic data declarations
let x = 5; // i32
let y: f64 = 3.14; // explicit type
let mut z = 10; // mutable
Control Flow
Loops and conditions
if x > 0 { "positive" }
for i in 0..5 { }
while condition { }
Functions
Function definitions
fn add(a: i32, b: i32) -> i32 {
a + b
}
Collections
Vectors, arrays, hashmaps
let vec = vec![1, 2, 3];
let arr = [1, 2, 3];
let mut map = HashMap::new();
🔹 Variables and Data Types
Essential variable declarations and common data types:
// Variable declarations
let immutable = 42; // Cannot change
let mut mutable = 42; // Can change
const CONSTANT: i32 = 42; // Compile-time constant
// Primitive types
let integer: i32 = -42; // 32-bit signed integer
let unsigned: u32 = 42; // 32-bit unsigned integer
let floating: f64 = 3.14; // 64-bit float
let boolean: bool = true; // Boolean
let character: char = '🦀'; // Unicode character
let string_slice: &str = "Hello"; // String slice
let owned_string: String = String::from("Hello"); // Owned string
// Arrays and tuples
let array: [i32; 3] = [1, 2, 3]; // Fixed size array
let tuple: (i32, f64, char) = (42, 3.14, 'x'); // Tuple
fn main() {
println!("Integer: {}", integer);
println!("String: {}", string_slice);
println!("Array first: {}", array[0]);
println!("Tuple first: {}", tuple.0);
}
Output:
Integer: -42
String: Hello
Array first: 1
Tuple first: 42
🔹 Control Flow Patterns
Common control flow structures and patterns:
fn control_flow_examples() {
let number = 7;
// If expressions
let result = if number > 5 { "big" } else { "small" };
// Match expressions
let description = match number {
1 => "one",
2..=5 => "few",
6..=10 => "several",
_ => "many",
};
// For loops
for i in 0..3 {
println!("Count: {}", i);
}
// While loop
let mut counter = 0;
while counter < 3 {
println!("While: {}", counter);
counter += 1;
}
// Loop with break
let mut x = 0;
let value = loop {
x += 1;
if x == 3 {
break x * 2; // Return value from loop
}
};
println!("Result: {}, Description: {}, Value: {}", result, description, value);
}
Output:
Count: 0
Count: 1
Count: 2
While: 0
While: 1
While: 2
Result: big, Description: several, Value: 6
🔹 Functions and Closures
Function definitions and closure syntax:
// Basic function
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
// Function with multiple parameters
fn calculate(x: i32, y: i32, operation: char) -> i32 {
match operation {
'+' => x + y,
'-' => x - y,
'*' => x * y,
'/' => x / y,
_ => 0,
}
}
// Closures (anonymous functions)
fn closure_examples() {
let add = |a, b| a + b; // Simple closure
let multiply = |x: i32| x * 2; // With type annotation
let numbers = vec![1, 2, 3, 4, 5];
// Using closures with iterators
let doubled: Vec = numbers.iter().map(|x| x * 2).collect();
let sum: i32 = numbers.iter().sum();
let evens: Vec<&i32> = numbers.iter().filter(|&x| x % 2 == 0).collect();
println!("Add: {}", add(5, 3));
println!("Multiply: {}", multiply(4));
println!("Doubled: {:?}", doubled);
println!("Sum: {}", sum);
println!("Evens: {:?}", evens);
}
fn main() {
println!("{}", greet("Alice"));
println!("5 + 3 = {}", calculate(5, 3, '+'));
closure_examples();
}
Output:
Hello, Alice!
5 + 3 = 8
Add: 8
Multiply: 8
Doubled: [2, 4, 6, 8, 10]
Sum: 15
Evens: [2, 4]
🔹 Collections Cheatsheet
Working with vectors, arrays, and hash maps:
use std::collections::HashMap;
fn collections_examples() {
// Vectors (dynamic arrays)
let mut vec = vec![1, 2, 3];
vec.push(4);
vec.pop(); // Removes last element
// Arrays (fixed size)
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..4]; // [2, 3, 4]
// Hash Maps
let mut scores = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
// String operations
let mut s = String::from("Hello");
s.push_str(", World!");
s.push('!');
// Common operations
println!("Vector: {:?}", vec);
println!("Array slice: {:?}", slice);
println!("Alice's score: {:?}", scores.get("Alice"));
println!("String: {}", s);
// Iteration
for (name, score) in &scores {
println!("{}: {}", name, score);
}
for (i, value) in vec.iter().enumerate() {
println!("Index {}: {}", i, value);
}
}
Output:
Vector: [1, 2, 3]
Array slice: [2, 3, 4]
Alice's score: Some(95)
String: Hello, World!!
Alice: 95
Bob: 87
Index 0: 1
Index 1: 2
Index 2: 3
🔹 Error Handling Quick Reference
Essential error handling patterns:
// Option type for nullable values
fn find_user(id: u32) -> Option<String> {
if id == 1 {
Some("Alice".to_string())
} else {
None
}
}
// Result type for error handling
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err("Cannot divide by zero".to_string())
} else {
Ok(a / b)
}
}
fn error_handling_examples() {
// Handling Option
match find_user(1) {
Some(name) => println!("Found user: {}", name),
None => println!("User not found"),
}
// Using if let
if let Some(name) = find_user(1) {
println!("User exists: {}", name);
}
// Handling Result
match divide(10.0, 2.0) {
Ok(result) => println!("Division result: {}", result),
Err(error) => println!("Error: {}", error),
}
// Using unwrap_or for defaults
let user = find_user(999).unwrap_or("Guest".to_string());
println!("User: {}", user);
}
Output:
Found user: Alice
User exists: Alice
Division result: 5
User: Guest