Rust
Memory safety without garbage collection. Fast and fearless.
⚠ pattern-based checks (code is analyzed, not compiled)
About Rust
Rust is a systems language focused on safety and performance. Its ownership model catches memory bugs at compile time — no GC, no segfaults. Used in Firefox, Discord, Cloudflare, and the Linux kernel. NOTE: Code is checked by pattern matching, not compiled. Focus on idiomatic Rust.
Quick-reference cheat sheet
// Rust cheat-sheet
fn main() {
let x = 42; // immutable by default
let mut y = 10; // mut to make mutable
y += 1;
let name: &str = "ada"; // string slice
let owned: String = String::from("ada");
println!("Hello, {}!", name);
println!("x = {}, y = {}", x, y);
// Conditions are expressions
let kind = if x > 0 { "positive" } else { "non-positive" };
// Loops
for i in 0..5 { println!("{}", i); }
let nums = vec![1, 2, 3, 4];
let sum: i32 = nums.iter().sum();
// Option / Result
let maybe: Option<i32> = Some(5);
match maybe {
Some(n) => println!("got {}", n),
None => println!("nothing"),
}
}
fn add(a: i32, b: i32) -> i32 {
a + b // no semicolon = return
}
struct Point { x: i32, y: i32 }
impl Point {
fn new(x: i32, y: i32) -> Self { Point { x, y } }
}
// Traits
trait Greet { fn hello(&self) -> String; }
// Closures
let add1 = |x: i32| x + 1;
// Error handling with Result
fn parse_int(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>()
}
Tasks
- 01introHello, World!println!("Hello, World!");
- 02introlet and mutDeclare an immutable and a mutable variable.
- 03introPrimitive typesAnnotate i32, f64, bool.
- 04intro&str vs StringDeclare a slice and an owned String.
- 05easyFunction with returnWrite fn add(a: i32, b: i32) -> i32.
- 06easyif as an expressionAssign from if/else.
- 07easyFor loop with rangePrint 1..=10 using a range.
- 08easyloop with breakUse loop and break.
- 09easyTuplesDestructure a tuple.
- 10easyFixed-size arraysDeclare and index a [i32; 5].
- 11mediumSum a VecSum a vec! of i32 using iter().sum().
- 12mediumVec push and lenBuild a Vec dynamically.
- 13mediummatch expressionMatch on an i32 to print a label.
- 14mediumOption<T>Use Some / None and unwrap_or.
- 15mediumResult<T, E>Pattern-match a Result.
- 16mediumBorrow a StringPass &String to a function.
- 17mediumMutable referenceModify a Vec through &mut.
- 18hardDefine a structStruct Point and an impl block.
- 19mediumDefine an enumEnum with multiple variants.
- 20hardIterator: map + collectSquare each element of a Vec<i32>.
- 21hardIterator: filterKeep only even numbers.
- 22hardTrait + implDefine trait Greet with fn hello(&self).
- 23hardGeneric functionfn largest<T: PartialOrd>(list: &[T]) -> &T
- 24hardClosuresDefine and call a closure.
- 25hardString sliceTake a slice of a String.
- 26hardHashMapUse std::collections::HashMap.
- 27hardLifetimesAnnotate lifetimes on a function.
- 28hardBox for recursionRecursive enum with Box.
- 29hard? operatorPropagate errors with ?.
- 30medium#[derive(Debug)]Derive Debug to print a struct.
- 31easyVariable shadowingShadow a variable changing its type.
- 32easyTuple destructuringDestructure a tuple into bindings.
- 33easyIterate an arrayLoop with for over an array.
- 34easyWhile loop countdownCountdown using while.
- 35mediumloop returns valueReturn a value from loop via break.
- 36easyBuild a StringUse push_str and push.
- 37mediumString sliceTake a &str slice from a String.
- 38mediumMutable borrowPass &mut String to a function.
- 39mediumimpl methodAdd a method to a struct.
- 40mediumAssociated functionConstructor-like associated fn.
- 41mediumEnum with dataDefine an enum with variants holding data.
- 42mediumif let patternUse if let on Option.
- 43mediumIterator sumSum a Vec with iterators.
- 44mediummap + collectSquare numbers via iterator chain.
- 45mediumFilter even numbersKeep evens with .filter.
- 46hardDefine a traitTrait with default implementation.
- 47hardGeneric functionFind largest with PartialOrd bound.
- 48mediumClosureClosure capturing environment.
- 49mediumMatch on ResultHandle Result with match.
- 50hardfold accumulatorSum via fold.
- 51hardRc<T> shared ownershipShare ownership with Rc::clone.
- 52hardRefCell interior mutabilityMutate through RefCell<T>.
- 53hardSpawn a threadSpawn and join a thread.
- 54hardChannels (mpsc)Send a message through a channel.
- 55hardMutex<T>Lock a Mutex and mutate.
- 56hardTrait object dynVec of trait objects.
- 57hardzip + enumerateCombine iterator adapters.
- 58hardFrom for custom errorimpl From<ParseIntError> for MyError.
- 59hardasync fn + .awaitDefine an async function and await it.
- 60mediumno_std crateMark a crate as no_std for bare metal.
- 61mediumpanic_handler for bare metalDefine a #[panic_handler] that loops forever.
- 62medium#[no_mangle] entry pointExpose a _start symbol with C ABI.
- 63hardVGA buffer raw writeWrite a byte to the 0xb8000 VGA text buffer.
- 64hardVolatile write to MMIOUse core::ptr::write_volatile for memory-mapped I/O.
- 65medium#[repr(C)] for FFI layoutStable struct layout for C interop.
- 66mediumextern "C" function declarationCall a C library function (abs).
- 67mediumManual bitflag helpersSet and test bits with | and &.
- 68mediumNewtype pattern for safetyWrap u32 in struct UserId(u32).
- 69hardPhantomData markerCarry an unused type parameter with PhantomData.
- 70hardDereference a raw pointerRead through *const i32 inside unsafe.
- 71hardstatic mut + unsafe accessIncrement a static mut COUNTER.
- 72hardAtomicUsize counterLock-free counter with AtomicUsize.
- 73hardArc<Mutex<T>> across threadsShare mutable state safely between threads.
- 74hardmpsc channel send/recvPass values between threads with std::sync::mpsc.
- 75mediumCustom Drop impl (RAII)Run code when a value goes out of scope.
- 76hardSend + Sync trait boundRequire a generic type to be thread-safe.
- 77mediumwasm-bindgen exported fnExpose a Rust fn to JavaScript.
- 78hardImport a JS function into wasmDeclare extern "C" { fn log(s: &str); } via wasm-bindgen.
- 79easycrate-type = cdylibConfigure Cargo.toml for a wasm cdylib.
- 80mediumPlain wasm export (no bindgen)Export add(a,b) directly with #[no_mangle] extern "C".
- 81hardCapstone — Freestanding kernel skeletonCombine no_std, panic_handler, _start, and a VGA write.
