Rust Tutorial
Fast, safe systems programming without a garbage collector.
Getting started4 lessons
Basics18 lessons
- 5Variables and Typeslet, mut and types.
- 6If, Loop, While and ForControl flow.
- 7Mutability and Shadowinglet makes an immutable binding and let mut allows changes.
- 8Rust Data TypesScalar types: integers (i8 to i128, u8 to u128, isize, usize), floats (f32, f64), bool and.
- 9Integer Overflow and MethodsIn debug builds arithmetic overflow panics, and in release it wraps.
- 10Numbers and MathOperators + - * / %.
- 11Characters and Booleanschar is a Unicode scalar value written in single quotes.
- 12Tuples and ArraysA tuple groups values of different types and an array holds a fixed number of values of on.
- 13Variables and MutabilityVariables are immutable by default.
- 14ShadowingA new let with the same name shadows the old one and may change the type.
- 15Scalar TypesIntegers i8 to i128 and u8 to u128, floats f32 and f64, bool and char.
- 16Casting with asUse as to convert between numeric types.
- 17TuplesA tuple groups values of different types.
- 18ArraysArrays have a fixed length known at compile time.
- 19println! and Formattingprintln! uses {} for Display and {:?} for Debug.
- 20OperatorsArithmetic, comparison, logical and bitwise operators.
- 21Numbers and MathFloat methods: sqrt, powi, abs, floor, ceil, round.
- 22Overflow HandlingUse wrapping_, checked_, saturating_ and overflowing_ methods to choose overflow behaviour.
Strings6 lessons
- 23Rust StringsString is a growable owned string and &str is a borrowed slice.
- 24String Slicing and CharsSlice with byte ranges like &s[0..5], which panics inside a character.
- 25Formatting and to_stringformat! returns a String.
- 26String and &str&str is a borrowed view of text.
- 27String Methodscontains, replace, to_uppercase, trim, split, starts_with and parse are common.
- 28Chars and BytesStrings are UTF-8.
Control flow10 lessons
- 29Rust If and ElseConditions do not need parentheses but must be bool.
- 30Rust Matchmatch compares a value to patterns and the arms must cover every case.
- 31Rust Loopsloop repeats forever until break and can return a value.
- 32if let and while letif let matches one pattern without a full match.
- 33if Expressionsif is an expression and can return a value.
- 34loop, while and forloop repeats forever until break, while checks a condition and for walks iterators.
- 35Rangesa..b excludes b and a..=b includes it.
- 36matchmatch compares a value with patterns and must cover every case.
- 37if let and while letif let matches one pattern in a short form.
- 38Loop LabelsLabels name loops so break and continue can target an outer loop.
Functions8 lessons
- 39Rust FunctionsDeclare with fn.
- 40Returning Tuples and Early ReturnsReturn several values as a tuple, and use return for early exits.
- 41Rust ClosuresA closure is an anonymous function written with |params| body.
- 42RecursionA function can call itself.
- 43FunctionsFunctions use fn, typed parameters and an arrow for the return type.
- 44ClosuresClosures are anonymous functions that capture variables: |x| x + 1.
- 45Passing FunctionsPass functions or closures to other functions with generics or fn types.
- 46RecursionFunctions can call themselves.
Ownership and data14 lessons
- 47Ownership and BorrowingThe core idea.
- 48Structs and EnumsCustom types.
- 49Vectors and HashMapsGrowable collections.
- 50References and Borrowing Rules& borrows immutably and &mut borrows mutably.
- 51Move, Copy and CloneAssigning a heap value moves ownership.
- 52SlicesA slice borrows a part of a collection: &s[1..3] for strings and &v[..2] for vectors.
- 53LifetimesLifetimes tell the compiler how long references are valid.
- 54Box, Rc and RefCellBox puts a value on the heap.
- 55OwnershipEach value has one owner.
- 56Borrowing and References& borrows without taking ownership and &mut allows changes.
- 57Clone and Copyclone makes a deep copy.
- 58SlicesA slice borrows part of a collection: &v[1..3] or &s[0..2].
- 59Lifetimes IntroLifetimes tell the compiler how long references live.
- 60Box and the HeapBox<T> stores a value on the heap.
Collections and iterators12 lessons
- 61VectorsVec<T> is a growable list.
- 62HashMaps and the Entry APIHashMap stores key value pairs.
- 63HashSet, BTreeMap and VecDequeHashSet stores unique values, BTreeMap keeps keys sorted and VecDeque is a double ended qu.
- 64IteratorsIterators are lazy.
- 65Iterator PatternsCommon patterns: find, position, any, all, max, min_by_key, fold, flat_map and chaining.
- 66VectorsVec<T> is a growable array.
- 67HashMapHashMap stores key value pairs.
- 68HashSet and BTreeSetSets hold unique values.
- 69IteratorsIterators are lazy.
- 70More Iterator Methodsenumerate, zip, rev, any, all, find, position, fold and max are everyday tools.
- 71Sortingsort works on Vec.
- 72VecDeque and BinaryHeapVecDeque is a double ended queue and BinaryHeap keeps the largest item on top.
Structs, enums and modules12 lessons
- 73Struct Methods and Associated Functionsimpl blocks add methods that take &self or &mut self and associated functions such as new .
- 74Enums with DataEach enum variant can hold different data.
- 75Derive and Common Traits#[derive] generates implementations of Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd.
- 76Modules and Visibilitymod groups code and items are private by default.
- 77GenericsGenerics let code work with many types.
- 78StructsA struct names and groups fields.
- 79Methods with implimpl blocks add methods.
- 80EnumsAn enum is one of several variants, which may carry data.
- 81OptionOption<T> is Some(value) or None.
- 82Result and the ? operatorResult<T, E> is Ok or Err.
- 83Modulesmod groups code and pub makes items public.
- 84derive Attributes#[derive(...)] adds Debug, Clone, PartialEq and more automatically.
Errors and traits15 lessons
- 85Option and ResultNo null, no exceptions.
- 86Traits and GenericsShared behaviour.
- 87Panic, unwrap and expectpanic! stops the program.
- 88The ? Operator and Custom Errors? returns the error early from a function that returns Result.
- 89Trait Objects and dynBox<dyn Trait> stores values of different types behind one interface using dynamic dispatc.
- 90Operator Overloading and Default MethodsImplement std::ops traits such as Add to give + a meaning for your type.
- 91panic, unwrap and expectpanic! stops the program.
- 92Custom ErrorsImplement Display and Error for your own error type.
- 93TraitsA trait defines shared behaviour.
- 94Generics and Trait BoundsGeneric functions work for many types.
- 95Default, From and IntoDefault gives a standard value.
- 96Tests and Docs#[test] marks tests run by cargo test.
- 97Practice: Word FrequencyCount words with a HashMap.
- 98Practice: FizzBuzzUse match on a tuple.
- 99Practice: StatsCompute min, max and average with iterators.
Advanced RustPremium8 lessons
- 100Threadsstd::thread::spawn runs code on a new thread and join waits for it.
- 101Message Passing with Channelsmpsc channels send values between threads.
- 102Shared State with Arc and MutexArc is an atomic reference counted pointer for threads and Mutex gives exclusive access.
- 103Drop and RAIIWhen a value goes out of scope Rust calls its Drop implementation automatically.
- 104Advanced PatternsPatterns can destructure structs, tuples and nested enums, bind with @, ignore with .
- 105MacrosMacros generate code at compile time.
- 106Async Rustasync fn returns a Future that runs when awaited on an executor such as Tokio.
- 107Unsafe Rustunsafe lets you dereference raw pointers, call unsafe functions and implement unsafe trait.
Rust in practicePremium9 lessons
- 108Cargo and CratesCargo.toml lists dependencies, called crates, from crates.io.
- 109Testing in RustUnit tests live next to the code in a tests module marked #[cfg(test)].
- 110JSON with serdeserde serialises and deserialises data.
- 111Files and Inputstd::fs reads and writes files, and std::io reads input.
- 112Web Servers with AxumAxum, Actix Web and Rocket build web services.
- 113Command Line Toolsstd::env::args reads arguments, and the clap crate parses flags and subcommands with deriv.
- 114Performance and ProfilingBuild with --release for speed.
- 115WebAssembly and FFIRust compiles to WebAssembly with wasm-pack to run in browsers, and calls C code through e.
- 116Rust Best PracticesRun cargo fmt and cargo clippy, prefer borrowing to cloning, use Result for errors, write .