Rust Cheatsheet
Language: Rust | Reference Guide
# 1. Basics & Variables
// Variables are immutable by default
let immutable_var = 5;
// Use `mut` to make a variable mutable
let mut mutable_var = 10;
mutable_var = 11;
// Basic data types (type annotations are often optional)
let an_integer: i32 = 42;
let a_float: f64 = 3.14;
let is_rust_fun: bool = true;
let a_char: char = '🦀';
// Tuples (fixed-size collection of different types)
let person: (&str, i32) = ("Alice", 30);
println!("{} is {} years old.", person.0, person.1);
// Arrays (fixed-size collection of the same type)
let numbers: [i32; 3] = [1, 2, 3];
println!("First number: {}", numbers[0]);
# 2. Control Flow
let number = 6;
if number % 4 == 0 {
println!("Number is divisible by 4");
} else if number % 3 == 0 {
println!("Number is divisible by 3");
} else {
println!("Number is not divisible by 4 or 3");
}
// `if` is an expression
let condition = true;
let x = if condition { 5 } else { 6 };
// Loops
// `loop` - infinite loop
let mut count = 0;
loop {
println!("Again!");
if count == 2 { break; }
count += 1;
}
// `for` loop - for iterating over collections
let a = [10, 20, 30];
for element in a.iter() {
println!("The value is: {}", element);
}
# 3. Ownership & Borrowing
// Ownership: Each value has a single owner.
// When the owner goes out of scope, the value is dropped.
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2, s1 is no longer valid
// println!("{}", s1); // This would cause a compile error
// Borrowing: You can borrow a reference to a value
let s3 = String::from("world");
fn calculate_length(s: &String) -> usize {
s.len()
}
let len = calculate_length(&s3); // Pass a reference
println!("The length of '{}' is {}.", s3, len); // s3 is still valid
// Mutable Borrows
let mut s4 = String::from("foo");
fn change(some_string: &mut String) {
some_string.push_str(", bar");
}
change(&mut s4);
println!("{}", s4); // "foo, bar"
# 4. Structs & Enums
// Struct: a custom data type
struct User {
username: String,
email: String,
active: bool,
}
let user1 = User {
email: String::from("user@example.com"),
username: String::from("someuser123"),
active: true,
};
// Enum: can be one of several possible values
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// The `Option` enum is very common
let some_number = Some(5);
let no_number: Option<i32> = None;
# 5. Pattern Matching with `match`
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
// Matching with Option<T>
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five); // Some(6)
let none = plus_one(None); // None
# 6. Error Handling
use std::fs::File;
use std::io::ErrorKind;
// Rust uses the `Result<T, E>` enum for recoverable errors.
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => {
panic!("Problem opening the file: {:?}", other_error)
}
},
};
// The `?` operator is a shortcut for propagating errors.
fn read_username_from_file() -> Result<String, std::io::Error> {
let mut s = String::new();
File::open("username.txt")?.read_to_string(&mut s)?;
Ok(s)
}
# 7. Common Collections
// Vector (Vec<T>): a growable list
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
// String: a growable, UTF-8 encoded string
let mut s = String::from("foo");
s.push_str("bar");
// HashMap<K, V>: stores key-value pairs
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
# 8. Cargo - Rust's Package Manager
# Create a new binary project
cargo new my_project
# Create a new library project
cargo new --lib my_library
# Build the project
cargo build
# Build for release (with optimizations)
cargo build --release
# Run the project's binary
cargo run
# Run tests
cargo test
# Check for errors without compiling
cargo check
# Add a dependency (edits Cargo.toml)
cargo add serde --features derive
Find more developer cheatsheets, guides, and resources at:
10xdev.blog/cheatsheets
master*
0
0
UTF-8
LF
Rust