Rust 131 🦀 Cheatsheet
1. Toolchain & Cargo
cargo new my_app # Create binary project
cargo new --lib my_lib # Create library project
cargo add serde --features derive
cargo check # Fast type-check
cargo clippy -- -D warnings
cargo fmt
cargo test
cargo build --release
cargo fix --edition # Migrate edition
rustup update stable
rustup target add aarch64-unknown-linux-gnu
cargo build --target aarch64-unknown-linux-gnu
2. Variables & Mutability
let x = 5; // Immutable
let mut y = 10; // Mutable
const MAX: u32 = 100; // Compile-time constant
static GLOBAL: i32 = 0; // Static variable
// Shadowing
let spaces = " ";
let spaces = spaces.len(); // Type changes allowed
3. Primitives & Types
// Scalars
i8, i16, i32, i64, i128, isize
u8, u16, u32, u64, u128, usize
f32, f64
bool
char // 4 bytes, Unicode scalar value
// Compound
let tup: (i32, f64, u8) = (500, 6.4, 1);
let arr: [i32; 3] = [1, 2, 3];
let slice: &[i32] = &arr[..];
4. Strings
let s1 = String::from("hello"); // Heap allocated
let s2 = "world"; // &str (string slice)
let s3 = s1 + " " + s2; // s1 moved, s2 borrowed
let s4 = format!("{} {}", s1, s2);
// Common methods
s1.len(); s1.is_empty(); s1.push('x'); s1.push_str("y");
s1.as_bytes(); s1.chars();
5. Ownership & Borrowing
// Move
let s1 = String::from("hello");
let s2 = s1; // s1 is invalid here
// Clone (deep copy)
let s3 = s2.clone();
// Borrowing (References)
let s4 = String::from("hi");
let len = calculate_length(&s4); // Immutable borrow
// Mutable Borrowing (Only one at a time)
let mut s5 = String::from("hi");
change(&mut s5);
fn calculate_length(s: &String) -> usize { s.len() }
fn change(s: &mut String) { s.push_str(" there"); }
6. Structs & Enums
struct User { active: bool, username: String }
// Tuple struct
struct Point(i32, i32);
// Methods & Associated Functions
impl User {
fn new(name: String) -> Self {
Self { active: true, username: name }
}
fn deactivate(&mut self) { self.active = false; }
}
// Enums
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
7. Pattern Matching
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Quarter(state) => { println!("State: {:?}", state); 25 },
}
// If-let
if let Some(x) = option { println!("{}", x); }
// Let-else (Stable)
let Some(x) = option else { return; };
// While-let
while let Some(top) = stack.pop() { ... }
8. Traits & Generics
trait Summary {
fn summarize(&self) -> String;
// Default implementation
fn preview(&self) -> String { format!("Read more...") }
}
impl Summary for NewsArticle {
fn summarize(&self) -> String { self.headline.clone() }
}
// Generic Bounds
fn notify<T: Summary + Display>(item: T) { ... }
// Or using where clause
fn notify<T>(item: T) where T: Summary + Display { ... }
// impl Trait (returning)
fn returns_summarizable() -> impl Summary { ... }
9. Smart Pointers
// Box (Heap allocation)
let b = Box::new(5);
// Rc (Reference counting, single thread)
use std::rc::Rc;
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
// Arc (Atomic, multi-thread)
use std::sync::Arc;
let c = Arc::new(5);
// RefCell (Interior mutability, runtime checks)
use std::cell::RefCell;
let num = RefCell::new(5);
*num.borrow_mut() += 1;
// Mutex (Multi-thread interior mutability)
use std::sync::Mutex;
let m = Mutex::new(5);
let mut num = m.lock().unwrap();
10. Error Handling
// Result
fn read_file() -> Result<String, std::io::Error> {
let mut f = std::fs::File::open("hello.txt")?; // ? propagates error
let mut s = String::new();
std::io::Read::read_to_string(&mut f, &mut s)?;
Ok(s)
}
// Option
let opt = Some(5);
let val = opt.unwrap_or(0);
// Custom Errors
#[derive(Debug)]
enum MyError { NotFound, ParseError }
11. Closures
// Traits: Fn, FnMut, FnOnce
let add = |a, b| a + b;
let mut count = 0;
let mut increment = || count += 1; // FnMut
let consume = move || drop(count); // FnOnce
12. Iterators
let v = vec![1, 2, 3];
let iter = v.iter(); // Yields &T
let iter_mut = v.iter_mut(); // Yields &mut T
let into_iter = v.into_iter(); // Yields T (moves)
// Adapters (lazy)
.map(|x| x * 2)
.filter(|x| x > &2)
.zip(other_iter)
.enumerate()
.chain(other_iter)
.take(5)
.skip(2)
.flatten()
.flat_map(|x| 0..x)
.peekable()
// Consumers (eager)
.sum()
.product()
.count()
.min() / .max()
.min_by_key() / .max_by_key()
.fold(0, |acc, x| acc + x)
.any(|x| ...) / .all(|x| ...)
.position(|x| ...)
.find(|x| ...)
.collect::<Vec<_>>()
.for_each(|x| ...)
13. Threads & Concurrency
use std::thread;
use std::time::Duration;
let handle = thread::spawn(|| {
thread::sleep(Duration::from_millis(100));
42
});
handle.join().unwrap();
// Channels
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || { tx.send(42).unwrap(); });
println!("{}", rx.recv().unwrap());
14. Unsafe & FFI
unsafe {
let p: *const i32 = &5;
println!("{}", *p);
}
// Extern functions
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
// Exporting to C (Edition 2024)
#[unsafe(no_mangle)]
pub extern "C" fn call_from_c() { ... }
15. Lifetimes
// Explicit lifetime in struct
struct Excerpt<'a> {
part: &'a str,
}
// Function bounding
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Static
let s: &'static str = "I live forever";
16. Macros
// Declarative (macro_rules!)
macro_rules! say_hello {
() => { println!("Hello!") };
}
say_hello!();
// Common built-in macros
println!(); print!(); format!();
vec![]; assert!(); assert_eq!();
panic!(); todo!(); unimplemented!();
include_str!(); include_bytes!();
dbg!(expr); // Prints file/line + value, returns value
17. Edition 2024 Changes
unsafe fnbodies require explicitunsafe {}blocks.externblocks requireunsafe extern.#[no_mangle]requires#[unsafe(no_mangle)].static mutreferences are a hard error.if lettemporaries drop beforeelse.genis a reserved keyword.- Range syntax
0..10remains, butcore::rangetypes (Rust 1.96) offerCopy-ableIntoIteratoralternatives. assert_matches!()is stabilized (Rust 1.96).
18. Cargo.toml Profile Settings
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = "symbols"
[profile.dev]
opt-level = 1
debug = 2
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!