Rust for Kids

Logo

Author: Miquel Cabot (miquel@cabot.dev)

Rust for Kids is an educational project designed to introduce the Rust programming language to young learners in a fun, accessible, and interactive way. Using a combination of mdBook and Reveal.js, this book blends storytelling, visual slides, and hands-on coding examples to teach core programming concepts through Rust. Whether you're a teacher, parent, or curious kid, this resource aims to make systems programming approachable and enjoyable. One small Rustacean step at a time!

Read the Book

We suggest the online version for general use, but cloning, installing, and building this book offline is a great option on-the-go.

Hosted Online

The latest version is hosted at: https://cabot.dev/rustforkids

Build Offline

You need to install rust before you can continue.

In order to make your life easy ๐Ÿ˜‰, there is a set of tasks that use cargo make.

With cargo make installed, you can list all tasks included to facilitate further installation, building, serving, formatting, and more with:

# Run from the top-level working dir of this repo
makers --list-all-steps

The tasks should be self-explanatory, if they are not - please file an issue to help us make them better.

License

All materials found within this repository are licensed under Mozilla Public License Version 2.0 - See the License for details.

Open slides

Preface


Dedicated to my son, Joan, and my daughter, Aina, who inspire me every day to make learning fun and exciting. ๐Ÿ’–


๐Ÿ‘‹ Welcome to Rust for Kids

Have you ever wondered how video games, robots, or websites are built? Or how your computer understands what to do when you click a button or type a word?

In this book, you'll start from the very beginning: learning how computers store files, follow instructions, and even speak in binary! Then we'll dive into Rust, a fun, powerful programming language that's used in everything from spaceships to video games.

This book is designed especially for kids, teens, parents, and curious beginners. No experience needed. Just bring your imagination and a little curiosity. ๐Ÿง โœจ


๐Ÿฆ€ Why Rust?

Rust is different from many other programming languages. Here's why we love it:

  • โœ… Fast and efficient: used in real-world systems like Firefox and Linux.
  • ๐Ÿง  Safe by design: it helps prevent bugs before they happen!
  • โค๏ธ Friendly: it has a great community and excellent documentation.
  • ๐Ÿงฐ Modern tooling: with tools like cargo, building projects is easy and fun.
  • ๐ŸŒ Versatile: you can build websites, games, robots, or even blockchains.

Plus... it has a super cute mascot: Ferris the Crab! ๐Ÿฆ€


  • The Rust Programming Language, by Steve Klabnik and Carol Nichols Read online

The Rust Programming Language

This is the official book for grown-ups who want to master Rust. We recommend it for parents, teachers, or older kids who want to go deeper after this book.


๐Ÿ“˜ Other Great Programming Books

These books are for older readers who want to become better software engineers over time:

  • Code Complete: A Practical Handbook of Software Construction, Second Edition, Steve McConnell
  • The Pragmatic Programmer: Your Journey to Mastery, David Thomas i Andrew Hunt
  • Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin

Books for developers


๐Ÿš€ Ready?

By the end of this journey, you'll know how to:

  • Navigate your computer's filesystem like a pro
  • Count in binary like a robot ๐Ÿค–
  • Write your own programs using Rust
  • Build small games and command-line tools
  • Think like a real systems programmer

Let's go! One small Rustacean step at a time... ๐Ÿฆ€๐Ÿ‘ฃ

Meet the Computer

Before we start coding in Rust, let's take a little tour of the magical machine we'll be working with: ๐Ÿง  the computer!

In this chapter, you'll learn:

  • ๐Ÿงฑ What a computer is made of. Including its brain (CPU), memory (RAM), and how it stores stuff (storage).
  • ๐Ÿ—‚๏ธ How computers organize information using files and folders.
  • ๐Ÿ’ป How to use the terminal. A secret door where you type commands and talk to your computer like a real programmer.
  • ๐Ÿ”ข How computers think in binary. Just 1s and 0s, like tiny light switches turning on and off.

By the end of this section, you'll have x-ray vision for how your device works and be ready to write your very first lines of code. Let's peek inside the machine! ๐Ÿ‘€โš™๏ธ

Open slides

The Computer's Brain (Hardware vs Software)


๐Ÿง  What's Inside a Computer?

A computer might look like just a box with a screen and keyboard... But inside, it's full of tiny parts that work together to follow instructions, store data, and show you cool stuff!


๐Ÿงฑ Two Main Parts

Every computer is made of two main ideas:

๐Ÿ’พ Hardware

These are the physical parts you can touch.

  • ๐Ÿง  CPU (Central Processing Unit): The brain of the computer. It thinks really fast.
  • ๐Ÿงฎ RAM (Memory): Temporary space to remember things while working.
  • ๐Ÿ—ƒ๏ธ Storage (like a hard drive): Where files and programs live when you're not using them.
  • ๐Ÿ–ฑ๏ธ Input devices: Keyboard, mouse, microphone: things you use to talk to the computer.
  • ๐Ÿ–ฅ๏ธ Output devices: Monitor, speakers, printer: the computer's way to talk back!

---v

Computer components


๐Ÿ“œ Software

Software is made of code: instructions written by humans.

It tells the hardware what to do! Like:

  • "Draw a picture"
  • "Play a sound"
  • "Open this folder"
  • "Run this game"

Rust is a language used to write this code. ๐Ÿฆ€


๐Ÿ” How It All Works Together

Imagine:

  1. You press a key (๐Ÿ“ฅ input)
  2. The keyboard sends a message to the CPU (๐Ÿง )
  3. The CPU checks the program (๐Ÿ“œ software)
  4. The screen shows a letter (๐Ÿ“ค output)

It happens in a blink, but it's all hardware and software working together!


๐Ÿงช Try This!

Think of another machine (like a microwave or robot toy). Can you name its input, output, memory, and "brain"?

(Write it down or discuss with a friend!)


โœ… Summary

  • A computer has hardware (the parts) and software (the code).
  • The CPU is the brain. It works with memory and storage to follow instructions.
  • You give the computer commands (input) and it gives you results (output).
  • With Rust, you'll soon write your own software to control this amazing machine!

Let's explore the filesystem next!

Open slides

The File System and the Command Line


๐Ÿ—‚๏ธ What Are Files and Folders?

Your computer is like a big library ๐Ÿ“š. Inside it are:

  • Files ๐Ÿ“„ โ†’ documents, pictures, music, code, and more.
  • Folders ๐Ÿ“ โ†’ containers to help organize your files.

You can put files inside folders, and folders inside other folders. Just like boxes inside boxes!


๐Ÿ–ฅ๏ธ Different Operating Systems

There are three main types of operating systems (OS):

  • ๐Ÿง Linux: free, open-source, used on many servers and by programmers.
  • ๐ŸŽ macOS: used on Apple computers.
  • ๐ŸชŸ Windows: very common in schools and offices.

They all do the same basic things, but the way you use the terminal or navigate folders might look a little different.


๐Ÿ“Œ This Book Uses: Linux & macOS

To keep things simple, this book focuses on:

  • โœ… Linux (like Ubuntu or Debian)
  • โœ… macOS (on a MacBook or iMac)

If you're using Windows, don't worry! You can still follow along.


๐Ÿ’ก Windows Users: Use WSL

To get a Linux-like terminal on Windows, install:

๐Ÿ”ง WSL (Windows Subsystem for Linux) It lets you run Linux commands inside Windows. You can install it by following this guide: ๐Ÿ‘‰ https://learn.microsoft.com/en-us/windows/wsl/

Once installed, you'll be able to use the same terminal commands we use in this book.


๐Ÿ  The Home Directory

Every user has a personal home directory. It's like your bedroom in the computer's house.

  • On Linux/macOS, it looks like:
/home/alex/

or

/Users/alex/

This is where all your stuff (documents, downloads, code) lives.


๐Ÿ“œ Paths and File Extensions

  • A path tells the computer where something is.

    • Example: /home/alex/projects/rust_for_kids/main.rs
  • A file extension tells what kind of file it is:

  • .txt โ†’ text

  • .jpg โ†’ image

  • .rs โ†’ Rust code

  • .exe โ†’ Windows program


๐Ÿ’ป The Terminal is a Magic Door ๐Ÿง™โ€โ™‚๏ธ

The terminal (or "command line") is a tool to talk directly to your computer.

You don't click, you type! It's like writing spells.

Programmers love the terminal because it's powerful and fast.


๐Ÿ”ค Terminal Command Cheat Sheet

CommandWhat it does
pwdShow where you are right now
lsList everything in the current folder
cd foldernameEnter a folder
cd ..Go up one level (to the parent folder)
cd .Stay where you are (the "current directory")
mkdir my_folderMake a new folder
touch hello.txtCreate a new empty file
cat hello.txtShow what's inside the file
rm file.txtDelete a file (โš ๏ธ careful!)
mv file.txt newname.txtRename a file
mv file.txt folder/Move a file into a folder
clearClean the screen

Tip: You can press the up arrow โ†‘ to repeat your last command!


๐Ÿงญ Terminal Challenge!

Try this in your terminal:

mkdir rust_games
cd rust_games
touch hello.txt
cat hello.txt

You're now a file system explorer!


๐Ÿงญ Mini Terminal Adventure

Try this:

mkdir my_story
cd my_story
touch chapter1.txt
echo "Once upon a time..." > chapter1.txt
cat chapter1.txt
mv chapter1.txt intro.txt
cd ..
ls

You just:

  • โœ… created a folder
  • โœ… entered it
  • โœ… created and edited a file
  • โœ… renamed the file
  • โœ… went back up a folder
  • โœ… listed what's there!
Open slides

The Language of Machines: Binary Basics


๐Ÿง  What Is a Bit?

A bit is the smallest piece of data a computer can store.

It can only be 1 (on ๐Ÿ’ก) or 0 (off โšซ), like a flashlight switch!

A byte is a group of 8 bits. With 8 bits, we can count from 0 to 255 because:

2^8 = 256

๐Ÿงฎ Decimal vs Binary

We usually count in decimal (base 10):

Digit PositionSixthFifthFourthThirdSecondFirst
Power of 1010โต10โด10ยณ10ยฒ10ยน10โฐ
Decimal Value100000100001000100101
Digit654321

Each digit is worth 10 times more than the one next to it (1, 10, 100...).


But computers count in binary (base 2):

We use only 0 and 1 (base 2):

Bit Position8th7th6th5th4th3rd2nd1st
Power of 22โท2โถ2โต2โด2ยณ2ยฒ2ยน2โฐ
Decimal Value1286432168421
Example Bits01010101

This is what 01010101 means:

Just add up the positions where there's a 1 to get the number!

01010101 โ†’ 64 + 16 + 4 + 1 = 85


๐Ÿงฎ Binary Conversion Table

Here are the first 16 numbers in decimal and binary

DecimalBinaryDecimalBinary
0000081000
1000191001
20010101010
30011111011
40100121100
50101131101
60110141110
70111151111

Try finding your age in binary!

๐Ÿ”ข Tip: With 4 bits, you can count from 0 to 15. That's 2โด = 16 combinations!


๐Ÿ”ค What About Letters?

Computers also store text as numbers, using something called ASCII.

For example:

CharacterASCII DecimalBinary
A6501000001
B6601000010
C6701000011
a9701100001

So "Hi" = 01001000 01101001 in binary!


๐Ÿ’พ Bytes, Kilobytes, Megabytesโ€ฆ

Let's zoom out!

UnitDescription
1 Byte= 8 bits
1 Kilobyte= 1024 Bytes
1 Megabyte= 1024 KB
1 Gigabyte= 1024 MB
1 Terabyte= 1024 GB
1 Petabyte= 1024 TB

Binary Numbers for Kids


๐Ÿงช Try This!

  1. Write the number 7 in binary
  2. Convert the word OK to ASCII + binary
  3. What's the biggest number you can make with 8 bits?
  4. Find the binary for the word RUST

โœ… Summary

  • Computers only understand 1s and 0s: binary.
  • A bit is one 1/0; a byte is 8 bits.
  • We use ASCII to turn text into numbers.
  • Memory is measured in units like KB, MB, GB, TB, etc.

Welcome to Rust

Now that you know how computers work and how they think, it's time to start programming! In this section, you'll meet Rust, a fast, fun, and powerful language used by real engineers all over the world. And now, by you! ๐ŸŽ‰

We'll guide you through installing Rust, writing your first "Hello, world!" program, and learning the most important building blocks: variables, data types, functions, and loops. Along the way, you'll discover how to make decisions in code, repeat actions, and add helpful comments that make your programs easier to understand. Step by step, you'll become a real Rustacean, someone who speaks computer with claws! ๐Ÿฆ€๐Ÿ’ป

Let's dive in!

Open slides

Installing Rust


๐Ÿš€ Let's Get Started!

To write Rust programs, we need to install:

  • ๐Ÿฆ€ rustc: the Rust compiler
  • ๐Ÿ“ฆ cargo: the Rust project manager (like a magic toolbox)

These tools come together in something called rustup.


๐Ÿ› ๏ธ Step 1: Install Rust

Open your terminal and paste this command:

curl https://sh.rustup.rs -sSf | sh

Then follow the instructions that appear.

โœ… Works on Linux, macOS, and WSL (Windows Subsystem for Linux)


๐ŸŒ Alternative Options

If you don't want to install anything locally, you can use:

  • Google Cloud Shell: a free cloud-based terminal and editor.
    • โž• Great for coding from anywhere
    • โš ๏ธ You'll still need to install Rust manually with rustup
  • Rust Playground: a browser-based Rust editor for quick experiments.
    • โž• No installation needed
    • โž– Limited to small examples and no file system access

Perfect for testing or learning on the go! ๐Ÿš€


๐Ÿงช Step 2: Check the Installation

Once it's done, check that everything works:

rustc --version
cargo --version

You should see something like:

rustc 1.xx.x
cargo 1.xx.x

๐Ÿ“ Step 3: Write Your First Rust Program!

Let's create a folder for our first project:

cargo new hello_rust
cd hello_rust

Now open the file src/main.rs and you'll see:

fn main() {
    println!("Hello, world!");
}

โ–ถ๏ธ Step 4: Run Your Program

In the same folder, run:

cargo run

You should see:

   Compiling hello_rust v0.1.0
    Finished dev [unoptimized + debuginfo]
     Running `target/debug/hello_rust`
Hello, world!

๐ŸŽ‰ Congratulations! You just wrote and ran your first Rust program!


โœ… Summary

  • Installed Rust with rustup
  • Verified rustc and cargo are working
  • Created a new project with cargo new
  • Ran your first Rust code with cargo run

Let's move on and learn what this code means! ๐Ÿฆ€๐Ÿ’ก

Open slides

Hello, Rustacean!


๐Ÿ‘‹ Hello, World!

Now that Rust is installed... Let's write your first program!

Open the main.rs file inside your project folder (hello_rust/src/main.rs), and you'll see this:

fn main() {
    println!("Hello, world!");
}

Let's break it down...


๐Ÿงฑ Anatomy of a Rust Program

fn main() {
    println!("Hello, world!");
}
  • ๐Ÿ”น fn means function
  • ๐Ÿ”น main() is where the program starts
  • ๐Ÿ”น { ... } is a code block
  • ๐Ÿ”น println! prints a message to the terminal
  • ๐Ÿ”น "Hello, world!" is a string
  • ๐Ÿ”น ! means it's a macro
  • ๐Ÿ”น Every line ends with a semicolon ;

๐Ÿ–จ๏ธ What is println!?

println! is a macro that prints text to the screen.

#![allow(unused)]
fn main() {
println!("Hello, Rustacean!");
}

You can print anything inside the quotes!

Example:

#![allow(unused)]
fn main() {
println!("My favorite number is {}", 42);
}

The {} gets replaced with the value. It's like a mini magic placeholder!


๐Ÿ’ฌ Add Some Comments

Comments are notes for humans. Rust ignores them.

You write them like this:

#![allow(unused)]
fn main() {
// This is a single-line comment

/*
This is a
multi-line comment
*/
}

Comments help you explain what your code does!


โœจ Challenge Time!

Try changing your code:

  • โœ… Print your name
  • โœ… Print your age
  • โœ… Print something in your own language
  • โœ… Add a comment that explains what you did

โœ… Summary

  • You wrote your first Rust program!
  • Learned about fn, main, and println!
  • Understood how macros and strings work
  • Learned how to write comments
Open slides

Variables: Your Code's Memory


๐Ÿ“ฆ What is a Variable?

A variable is like a box ๐Ÿงฐ with a name, where you can store a value.

In Rust, we use the keyword let to create one:

#![allow(unused)]
fn main() {
let age = 10;
}

This means: "Create a box named age and put the number 10 inside."


๐Ÿง  Variables Store Information

You can store different types of values:

#![allow(unused)]
fn main() {
let age = 10;               // i32 โ†’ integer
let name = "Alex";          // &str โ†’ text
let is_rust_fun = true;     // bool โ†’ true or false
}

Rust usually figures out the type for you (this is called type inference).

But you can also be explicit:

#![allow(unused)]
fn main() {
let score: i32 = 100;
let name: String = String::from("Zoe");
}

๐Ÿ”„ What If I Want to Change It?

Rust makes variables immutable by default: they cannot be changed.

#![allow(unused)]
fn main() {
let age = 10;
age = 11; // โŒ error!
}

If you want to change it, use mut (for "mutable"):

#![allow(unused)]
fn main() {
let mut age = 10; // Now it's mutable
age = 11; // โœ… now it works!
}

๐Ÿ’ก Tip: Rust helps you write safer code by making things immutable by default.


๐Ÿงช Mini Challenge

Try writing this in your main.rs:

#![allow(unused)]
fn main() {
let mut score = 0;
println!("Score: {}", score);

score = 5;
println!("New score: {}", score);
}

๐Ÿง  Common Variable Types

TypeExampleDescription
i32let x = 5;Integer (32-bit number)
boollet done = true;True or false
Stringlet name = String::from("Zoe");Text (owned string)

Rust is a statically typed language: every variable has a type!


โœ… Summary

  • Variables hold information: like numbers, text, or true/false values
  • Use let to create variables
  • Use mut to make them changeable
  • Rust has powerful, safe types like i32, bool, and String
Open slides

Data Types: The Building Blocks of Rust


๐Ÿงฑ What Are Data Types?

A data type tells the computer what kind of value a variable holds.

In Rust, every value has a type:

  • Numbers? ๐Ÿงฎ
  • Text? ๐Ÿ“
  • Yes or no? โœ…โŒ
  • Groups of values? ๐Ÿ“ฆ

Rust uses types to make sure your program is correct and safe.


๐Ÿ”ข Scalar Types

These types hold just one value.

TypeExampleDescription
i32let x = 10;Integer
f64let pi = 3.14;Decimal (floating point)
boollet is_ok = true;True or false
charlet letter = 'A';A single character or symbol

Rust gives you many number types (i8, u32, f32, etc.), but i32 and f64 are the defaults.


๐Ÿ”ข Integer Types

  • An integer is a whole number (no decimals!).
  • Rust gives you options based on:
    • how big the number can be (8, 16, 32, 64, 128 bits)
    • and whether it can be negative
  • Signed integers allow negative numbers:
#![allow(unused)]
fn main() {
let x: i32 = -42;
}
  • Common signed types:
    • i8, i16, i32, i64, i128
    • isize (size depends on your computer)

โž• Unsigned Integers

  • Unsigned integers* can only store positive numbers (or 0).
  • They're like regular integers but without the minus sign:
#![allow(unused)]
fn main() {
let points: u32 = 99;
}
  • The u means unsigned.
  • Common types:
    • u8, u16, u32, u64, u128
    • usize (size depends on your computer)

Use u* when you're sure the value can't be negative, like age or score!


๐ŸŒŠ Floating Point Numbers

  • Sometimes we need decimals, like 3.14, 99.99, or 0.5.
  • These are called floating-point numbers.
#![allow(unused)]
fn main() {
let price: f64 = 4.99;
}
  • Rust gives you:
    • f32 โ†’ less precise, smaller
    • f64 โ†’ more precise, default

Use f64 unless you have a special reason to save space.


๐Ÿ—ƒ๏ธ Composite Types

These hold multiple values.


๐Ÿ“ฆ Tuples

A tuple is a collection of values of different types:

#![allow(unused)]
fn main() {
let person = ("Zoe", 12, true);
}

Access values with a dot:

#![allow(unused)]
fn main() {
println!("{}", person.0); // Zoe
}

๐Ÿ“š Arrays

Arrays store many values of the same type:

#![allow(unused)]
fn main() {
let scores = [10, 20, 30];
}

Get values with square brackets:

#![allow(unused)]
fn main() {
println!("{}", scores[1]); // 20
}

Arrays have a fixed size in Rust.


๐Ÿง  Type Inference vs. Annotation

Rust usually guesses the type for you:

#![allow(unused)]
fn main() {
let age = 8;         // inferred as i32
let happy = true;    // inferred as bool
}

But you can also be clear:

#![allow(unused)]
fn main() {
let pi: f64 = 3.1415;
let letter: char = 'R';
}

๐Ÿงช Challenge Time!

  • โœ… Create a tuple with your name and age
  • โœ… Make an array with your 3 favorite numbers
  • โœ… Try creating a bool that says if Rust is fun
  • โœ… Write a char with your favorite emoji!

โœ… Summary

  • Scalar types: i32, f64, bool, char...
  • Composite types: tuple, array
  • Rust checks your types to keep your code safe
  • You can let Rust guess, or you can write the type yourself
Open slides

Functions: The Magic of Reusable Code


โœจ What Is a Function?

A function is a named block of code that does something.

It's like a spell you can use over and over again. ๐Ÿง™โ€โ™‚๏ธ

Example:

#![allow(unused)]
fn main() {
fn greet() {
    println!("Hello, Rustacean!");
}
}

To run the function, you call it:

#![allow(unused)]
fn main() {
greet();
}

๐Ÿงฑ The Structure of a Function

Here's what a basic function looks like:

#![allow(unused)]
fn main() {
fn say_hello() {
    println!("Hello!");
}
}
  • fn โ†’ means function
  • say_hello โ†’ the name
  • () โ†’ no input
  • { ... } โ†’ the code block

You can define many functions, but main() is always the one that runs first!


๐Ÿงฎ Functions With Parameters

Functions can take inputs:

#![allow(unused)]
fn main() {
fn greet(name: &str) {
    println!("Hello, {}!", name);
}
}

Call it like this:

#![allow(unused)]
fn main() {
greet("Zoe");
}

The name: &str means it expects a string slice (a bit of text).

๐ŸŽ Parameters are like ingredients you give to the function.


โž• Multiple Parameters in a Function

You can pass more than one input to a function!

Just separate them with commas:

#![allow(unused)]
fn main() {
fn add(a: i32, b: i32) {
    println!("Sum is: {}", a + b);
}
}

Call it like this:

#![allow(unused)]
fn main() {
add(3, 7); // Sum is: 10
}

๐Ÿ”™ Returning Values from a Function

Sometimes you want a function to give something back.

To do that, you define a return type and use the return keyword:

#![allow(unused)]
fn main() {
fn square(x: i32) -> i32 {
    return x * x;
}
}

Then you can save the result:

#![allow(unused)]
fn main() {
let result = square(5);
println!("5 squared is {}", result);
}

๐Ÿง  return Is Optional at the End

Rust allows you to skip return on the last line of a function:

#![allow(unused)]
fn main() {
fn square(x: i32) -> i32 {
    x * x  // no semicolon = return value
}
}

โ— Don't put a ; if you want to return the value!

โœ… This also works:

#![allow(unused)]
fn main() {
fn greet() -> String {
    String::from("Hello!")
}
}

๐Ÿงช Mini Challenge

Try this:

  • โœ… Write a function called say_name() that prints your name
  • โœ… Write a function add(a, b) that returns the sum of two numbers
  • โœ… Call both from main() and print the results

โœ… Summary

  • Functions let you organize and reuse code
  • Use fn name() { ... } to define them
  • You can give functions parameters and get back return values
  • Every program starts with the special fn main()
Open slides

Control Flow: Making Decisions in Code


๐Ÿค” What Is Control Flow?

Control flow is how your program makes decisions.

You can ask questions like:

  • Is the number bigger than 10?
  • Is it sunny today?
  • Is the user name correct?

Rust lets you use if, else, and match to control what happens!


๐Ÿ”€ if and else

#![allow(unused)]
fn main() {
let age = 10;

if age >= 18 {
    println!("You can vote!");
} else {
    println!("You are too young to vote.");
}
}
  • โœ… The condition goes in parentheses
  • โœ… The block runs only if the condition is true

๐Ÿ” else if

You can check multiple conditions:

#![allow(unused)]
fn main() {
let score = 75;

if score >= 90 {
    println!("A+");
} else if score >= 60 {
    println!("Passed!");
} else {
    println!("Try again!");
}
}

Rust checks conditions in order, top to bottom.


โœ… Boolean Expressions

Inside if (...), you can use:

ExpressionMeaning
x == 5x is equal to 5
x != 3x is NOT 3
age >= 18age is 18 or more
is_happy == trueis_happy is true (can omit)

Example:

#![allow(unused)]
fn main() {
if is_happy {
    println!("Yay!");
}
}

๐Ÿง  match: Superpower of if

match is like a smart switch-case.

#![allow(unused)]
fn main() {
let grade = 'B';

match grade {
    'A' => println!("Excellent!"),
    'B' => println!("Great!"),
    'C' => println!("Good."),
    _   => println!("Keep trying!"),
}
}
  • โœ… The _ means "anything else"
  • โœ… Every case uses => and ends with a comma

๐Ÿงช Mini Challenge

Try these in your main.rs:

  • โœ… Use if to check if a number is even or odd
  • โœ… Use else if to print a letter grade from a score
  • โœ… Use match to print a message for 'A', 'B', 'C', or 'F'

โœ… Summary

  • Use if, else, and else if to control what your program does
  • Conditions must be true or false
  • Use match when you have many possible values
  • Rust checks your logic to keep it safe and readable!
Open slides

Loops: Repeating Actions in Rust


๐Ÿ” What Is a Loop?

A loop is used when you want to do something over and over again.

Examples:

  • Count from 1 to 10
  • Print a message 3 times
  • Check a condition until it's false

Rust gives us 3 types of loops:

  • loop
  • while
  • for

โ™พ๏ธ loop: Repeat Forever (or Until You Break)

#![allow(unused)]
fn main() {
loop {
    println!("This will go on forever!");
}
}

โ— You must manually stop an infinite loop with break:

#![allow(unused)]
fn main() {
let mut counter = 0;

loop {
    println!("Count: {}", counter);
    counter += 1;

    if counter == 5 {
        break;
    }
}
}

๐Ÿ”„ while: Repeat While a Condition Is True

#![allow(unused)]
fn main() {
let mut number = 3;

while number > 0 {
    println!("{}!", number);
    number -= 1;
}

println!("Liftoff! ๐Ÿš€");
}

while checks the condition before each loop.


๐Ÿ”ข for: Loop Over a Range

#![allow(unused)]
fn main() {
for number in 1..4 {
    println!("Number: {}", number);
}
}

๐Ÿง  1..4 means: 1, 2, 3 (not including 4)

You can also include 4:

#![allow(unused)]
fn main() {
for number in 1..=4 {
    println!("Now: {}", number);
}
}

Use for when you know how many times to loop.


๐ŸŽฏ Understanding Ranges in Rust

A range is a way to say: "Start at this number, go up to (or through) that number."

๐Ÿงฎ Exclusive Range

#![allow(unused)]
fn main() {
1..4
}

Means: 1, 2, 3 (but not 4)

โœ… Inclusive Range

#![allow(unused)]
fn main() {
1..=4
}

Means: 1, 2, 3, 4 (includes 4)

---v

You can use them in for loops:

#![allow(unused)]
fn main() {
for n in 0..=5 {
    println!("{}", n);
}
}

---v

๐Ÿ” Ranges are not just for numbers โ€” they work with letters too!

#![allow(unused)]
fn main() {
for c in 'a'..='e' {
    println!("{}", c);
}
}

๐Ÿงช Mini Challenge

  • โœ… Use a loop to print numbers until you reach 10
  • โœ… Use a while loop to count down from 5 to 1
  • โœ… Use a for loop to print the letters A to Z (hint: use chars!)

โœ… Summary

  • loop runs forever unless you stop it with break
  • while runs while a condition is true
  • for is great for counting or looping through things
  • Rust gives you flexible, safe looping tools!

Rustacean Thinking

Now that you've learned the basics of writing Rust code, it's time to explore what makes Rust truly special. In this section, you'll dive into the core ideas that make Rust different and powerful.

You'll discover the magic behind ownership, Rust's unique way of managing memory safely and efficiently. You'll learn how to borrow values without copying them, how to work with mutable data, and how Rust helps you catch errors before your program even runs. We'll also explore how to build your own custom types using structs and enums, and how to use pattern matching to write smart and clean code.

These are the tools and ideas that real Rustaceans use every day, and soon, you will too! ๐Ÿฆ€๐Ÿš€

Open slides

Ownership: The Heart of Rust


Open slides

Borrowing and References: Sharing Without Copying


Open slides

The Power of Mutability


Open slides

Error Handling: Keeping Your Code Safe


Open slides

Structs: Custom Data Types in Rust


Open slides

Enums: Defining Your Own Types


Open slides

Pattern Matching: A Powerful Tool


๐Ÿ“š Resources

๐ŸŽ“ Resources for Students

๐Ÿ“– Cheatsheets and References

  • The Rust Programming Language, Steve Klabnik, Carol Nichols. No Starch Press; 2nd edition (2023)
  • Programming Rust: Fast, Safe Systems Development, Jim Blandy, Jason Orendorff, Leonora F S Tindall. O'Reilly Media; 2nd edition (2021)
  • Rust for Rustaceans: Idiomatic Programming for Experienced Developers, Jon Gjengset. No Starch Press; 1st edition (2021)
  • Rust in Action, Tim McNamara. Manning Publications; 1st edition (2021)

Mozilla Public License Version 2.0

1. Definitions

1.1. โ€œContributorโ€

means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.

1.2. โ€œContributor Versionโ€

means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution.

1.3. โ€œContributionโ€

means Covered Software of a particular Contributor.

1.4. โ€œCovered Softwareโ€

means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.

1.5. โ€œIncompatible With Secondary Licensesโ€

means

  1. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
  2. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.

1.6. โ€œExecutable Formโ€

means any form of the work other than Source Code Form.

1.7. โ€œLarger Workโ€

means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.

1.8. โ€œLicenseโ€

means this document.

1.9. โ€œLicensableโ€

means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.

1.10. โ€œModificationsโ€

means any of the following:

  1. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
  2. any new file in Source Code Form that contains any Covered Software.

1.11. โ€œPatent Claimsโ€ of a Contributor

means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.

1.12. โ€œSecondary Licenseโ€

means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.

1.13. โ€œSource Code Formโ€

means the form of the work preferred for making modifications.

1.14. โ€œYouโ€ (or โ€œYourโ€)

means an individual or a legal entity exercising rights under this License. For legal entities, โ€œYouโ€ includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, โ€œcontrolโ€ means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.

2. License Grants and Conditions

2.1. Grants

Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:

  1. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
  2. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.

2.2. Effective Date

The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.

2.3. Limitations on Grant Scope

The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:

  1. for any code that a Contributor has removed from Covered Software; or
  2. for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
  3. under Patent Claims infringed by Covered Software in the absence of its Contributions.

This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).

2.4. Subsequent Licenses

No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).

2.5. Representation

Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.

2.6. Fair Use

This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.

2.7. Conditions

Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.

3. Responsibilities

3.1. Distribution of Source Form

All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form.

3.2. Distribution of Executable Form

If You distribute Covered Software in Executable Form then:

  1. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
  2. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License.

3.3. Distribution of a Larger Work

You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).

3.4. Notices

You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.

3.5. Application of Additional Terms

You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.

4. Inability to Comply Due to Statute or Regulation

If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.

5. Termination

5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.

5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.

5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.

6. Disclaimer of Warranty

Covered Software is provided under this License on an โ€œas isโ€ basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.

7. Limitation of Liability

Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.

8. Litigation

Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims.

9. Miscellaneous

This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.

10. Versions of the License

10.1. New Versions

Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.

10.2. Effect of New Versions

You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.

10.3. Modified Versions

If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).

10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses

If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.

Exhibit A - Source Code Form License Notice

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://www.mozilla.org/en-US/MPL/2.0/.

If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.

You may add additional accurate notices of copyright ownership.

Exhibit B - โ€œIncompatible With Secondary Licensesโ€ Notice

This Source Code Form is โ€œIncompatible With Secondary Licensesโ€, as defined by the Mozilla Public License, v. 2.0.