Rust for Kids
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.
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! ๐ฆ
๐ Recommended Rust Book
- The Rust Programming Language, by Steve Klabnik and Carol Nichols Read online
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
๐ 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! ๐โ๏ธ
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
๐ 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:
- You press a key (๐ฅ input)
- The keyboard sends a message to the CPU (๐ง )
- The CPU checks the program (๐ software)
- 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!
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
- Example:
-
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
Command | What it does |
---|---|
pwd | Show where you are right now |
ls | List everything in the current folder |
cd foldername | Enter a folder |
cd .. | Go up one level (to the parent folder) |
cd . | Stay where you are (the "current directory") |
mkdir my_folder | Make a new folder |
touch hello.txt | Create a new empty file |
cat hello.txt | Show what's inside the file |
rm file.txt | Delete a file (โ ๏ธ careful!) |
mv file.txt newname.txt | Rename a file |
mv file.txt folder/ | Move a file into a folder |
clear | Clean 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!
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 Position | Sixth | Fifth | Fourth | Third | Second | First |
---|---|---|---|---|---|---|
Power of 10 | 10โต | 10โด | 10ยณ | 10ยฒ | 10ยน | 10โฐ |
Decimal Value | 100000 | 10000 | 1000 | 100 | 10 | 1 |
Digit | 6 | 5 | 4 | 3 | 2 | 1 |
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 Position | 8th | 7th | 6th | 5th | 4th | 3rd | 2nd | 1st |
---|---|---|---|---|---|---|---|---|
Power of 2 | 2โท | 2โถ | 2โต | 2โด | 2ยณ | 2ยฒ | 2ยน | 2โฐ |
Decimal Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
Example Bits | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 |
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
Decimal | Binary | Decimal | Binary |
---|---|---|---|
0 | 0000 | 8 | 1000 |
1 | 0001 | 9 | 1001 |
2 | 0010 | 10 | 1010 |
3 | 0011 | 11 | 1011 |
4 | 0100 | 12 | 1100 |
5 | 0101 | 13 | 1101 |
6 | 0110 | 14 | 1110 |
7 | 0111 | 15 | 1111 |
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:
Character | ASCII Decimal | Binary |
---|---|---|
A | 65 | 01000001 |
B | 66 | 01000010 |
C | 67 | 01000011 |
a | 97 | 01100001 |
So "Hi"
= 01001000 01101001
in binary!
๐พ Bytes, Kilobytes, Megabytesโฆ
Let's zoom out!
Unit | Description |
---|---|
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!
- Write the number
7
in binary - Convert the word
OK
to ASCII + binary - What's the biggest number you can make with 8 bits?
- 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!
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
andcargo
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! ๐ฆ๐ก
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
, andprintln!
- Understood how macros and strings work
- Learned how to write comments
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
Type | Example | Description |
---|---|---|
i32 | let x = 5; | Integer (32-bit number) |
bool | let done = true; | True or false |
String | let 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
, andString
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.
Type | Example | Description |
---|---|---|
i32 | let x = 10; | Integer |
f64 | let pi = 3.14; | Decimal (floating point) |
bool | let is_ok = true; | True or false |
char | let letter = 'A'; | A single character or symbol |
Rust gives you many number types (
i8
,u32
,f32
, etc.), buti32
andf64
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
meansunsigned
. - 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
, or0.5
. - These are called floating-point numbers.
#![allow(unused)] fn main() { let price: f64 = 4.99; }
- Rust gives you:
f32
โ less precise, smallerf64
โ 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
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 functionsay_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()
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:
Expression | Meaning |
---|---|
x == 5 | x is equal to 5 |
x != 3 | x is NOT 3 |
age >= 18 | age is 18 or more |
is_happy == true | is_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
, andelse 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!
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 withbreak
while
runs while a condition is truefor
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! ๐ฆ๐
Ownership: The Heart of Rust
Borrowing and References: Sharing Without Copying
The Power of Mutability
Error Handling: Keeping Your Code Safe
Structs: Custom Data Types in Rust
Enums: Defining Your Own Types
Pattern Matching: A Powerful Tool
๐ Resources
๐ Resources for Students
๐ Cheatsheets and References
๐ Featured Tutorials and Articles
- Introduction to the Rust State Machine. A practical introduction to the state machine in Rust, useful for understanding how to structure protocols or systems with phase changes.
๐ Recommended Books
- 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
- that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
- 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:
- any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
- 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:
- 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
- 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:
- for any code that a Contributor has removed from Covered Software; or
- 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
- 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:
- 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
- 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.