Rust Cheat Sheet
Rust is a systems programming language focused on safety, performance, and concurrency without a garbage collector. This Rust cheatsheet provides an example-driven reference covering core syntax, ownership, borrowing, lifetimes, and commonly used Rust language features.
Minimal Program
fn main() {
println!("Hello, Rust");
}
Variables & Mutability
let x = 10;
let mut y = 20;
y += 1;
Basic Types
i32
i64
u32
f64
bool
char
let a: i32 = 10;
let b: f64 = 3.14;
Shadowing
let x = 5;
let x = x + 1;
let x = x * 2;
Constants
const MAX: i32 = 100;
Control Flow
if
let r = if x > 10 { 1 } else { 0 };
match
match x {
1 => println!("one"),
2 => println!("two"),
_ => println!("other"),
}
Loops
for i in 0..5 {
println!("{}", i);
}
while x > 0 {
x -= 1;
}
loop {
break;
}
Functions
fn add(a: i32, b: i32) -> i32 {
a + b
}
let r = add(2, 3);
Ownership
let s1 = String::from("hello");
let s2 = s1;
let s3 = String::from("hello");
let s4 = s3.clone();
Borrowing
fn len(s: &String) -> usize {
s.len()
}
let s = String::from("text");
let l = len(&s);
Mutable Borrowing
fn push(s: &mut String) {
s.push('!');
}
let mut s = String::from("hi");
push(&mut s);
Lifetimes
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
Strings
let s = String::from("Rust");
let slice = &s[0..2];
let literal = "static str";
Arrays
let arr = [1, 2, 3];
arr[0];
Vectors
let mut v = vec![1, 2, 3];
v.push(4);
for n in &v {
println!("{}", n);
}
Tuples
let t = (1, "a", true);
let (x, y, z) = t;
Structs
struct Point {
x: i32,
y: i32,
}
let p = Point { x: 10, y: 20 };
Struct Methods
impl Point {
fn sum(&self) -> i32 {
self.x + self.y
}
}
Enums
enum Result<T, E> {
Ok(T),
Err(E),
}
Option & Result
let v: Option<i32> = Some(10);
match v {
Some(x) => x,
None => 0,
}
let r: Result<i32, &str> = Ok(5);
Error Handling
fn read() -> Result<String, std::io::Error> {
Ok(String::from("data"))
}
let value = read()?;
Traits
trait Speak {
fn speak(&self);
}
impl Speak for Point {
fn speak(&self) {
println!("point");
}
}
Generics
fn max<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
Trait Bounds
fn print<T: std::fmt::Debug>(v: T) {
println!("{:?}", v);
}
Closures
let add = |a, b| a + b;
add(2, 3);
Iterators
let sum: i32 = v.iter().sum();
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
Modules
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
math::add(2, 3);
Crates
use rand::Rng;
Ownership with Structs
struct User {
name: String,
}
let u = User { name: String::from("A") };
Concurrency (Threads)
use std::thread;
thread::spawn(|| {
println!("running");
});
Channels
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(42).unwrap();
let v = rx.recv().unwrap();
Mutex & Arc
use std::sync::{Mutex, Arc};
let data = Arc::new(Mutex::new(0));
File I/O
use std::fs;
fs::write("file.txt", "text").unwrap();
let content = fs::read_to_string("file.txt").unwrap();