Tsallaka zuwa abun ciki
Justice Tech School

Rust Tutorial

Fast, safe systems programming without a garbage collector.

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