Part 01 · Rust Is Not Scary

Why Rust Feels Hard (and Why It Is Not)

Compiler checksMemory safetyLearning curve

Rust is not harder, it is earlier: it shows you at compile time the bugs other languages let you find at 3 AM in production.

⏱ 9 min · Station 2 of 75

The story

Two teams build the same shop. One team has a relaxed senior who approves every pull request in a minute. The other has a strict senior who reads every line and sends back comments like "what if this coupon code doesn't exist?"

For the first month the strict team feels slow and a little annoyed. Then Eid arrives. The relaxed team gets a phone call at 3 AM: checkout is broken for anyone who typed a coupon code wrong. The strict team sleeps, because that question was asked and answered in review, weeks ago.

The Rust compiler is the strict senior. It is not making the work harder. It is asking the hard questions earlier, while you are still at your desk, instead of letting a customer ask them in production.

The idea

Every program has the same kinds of mistakes waiting in it: a value that might be missing, a number that might not fit, memory freed while something still uses it, two threads changing the same data. Languages differ in when you find out:

  • Python and JavaScript find out while the program runs, when that exact line happens with that exact data. Sometimes that is in a test. Sometimes it is a customer.
  • Rust checks for these whole families of mistakes before the program exists. If the check fails, there is no program to run, only an error message that says what is wrong and usually how to fix it.

So "Rust is hard" mostly means "Rust shows me all my bugs on day one". That feels like more work at first, because in other languages you would have met the same bugs later, spread over months, often at worse times.

Python / JavaScriptRustwritewritecompilecompiletesttestdeploydeploy3 AM3 AMbugbugfound by a customer, at 3 AMfound by the compiler, before anyone runs it
The same bug in two worlds. In Python or JavaScript it rides through compile, test and deploy and is found by a customer. In Rust the compiler stops it before the program exists.

Try it: the coupon bug

A shop gives 10% off with the code EID10. Here is the Python version. Look at what happens when a customer types EID100 by mistake:

COUPONS = {"EID10": 0.10}

def discount(code):
    return COUPONS.get(code)  # None when the code is unknown

def final_price(price, code):
    return price - price * discount(code)

print(final_price(500, "EID10"))
print(final_price(500, "EID100"))  # a customer types the code wrong
450.0
Traceback (most recent call last):
  File "/home/you/rust-lab/coupon.py", line 10, in <module>
    print(final_price(500, "EID100"))  # a customer types the code wrong
          ~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "/home/you/rust-lab/coupon.py", line 7, in final_price
    return price - price * discount(code)
                   ~~~~~~^~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

The first call works. The second crashes, because COUPONS.get("EID100") returns None, and Python only discovers that 500 * None makes no sense when it gets to that line. If no test typed a wrong code, the first person to find this bug is a customer at checkout.

Now the same program in JavaScript:

const COUPONS = { EID10: 0.1 };

function discount(code) {
  return COUPONS[code]; // undefined when the code is unknown
}

function finalPrice(price, code) {
  return price - price * discount(code);
}

console.log(finalPrice(500, "EID10"));
console.log(finalPrice(500, "EID100")); // a customer types the code wrong
Predict first

What does the JavaScript version print for the wrong code EID100?

450
NaN

This is worse than a crash. No error, no log line. The customer sees a total of NaN, or NaN gets saved into the orders table.

What the compiler says

In Rust, a function that might not have an answer says so in its return type. discount returns Option<f64>: either Some(0.10) or None. Here is a first try, treating that answer as a plain number:

fn discount(code: &str) -> Option<f64> {
    match code {
        "EID10" => Some(0.10),
        _ => None, // unknown code: no discount
    }
}

fn final_price(price: f64, code: &str) -> f64 {
    let d: f64 = discount(code);
    price - price * d
}

fn main() {
    println!("{}", final_price(500.0, "EID10"));
    println!("{}", final_price(500.0, "EID100"));
}
error[E0308]: mismatched types
 --> src/main.rs:9:18
  |
9 |     let d: f64 = discount(code);
  |            ---   ^^^^^^^^^^^^^^ expected `f64`, found `Option<f64>`
  |            |
  |            expected due to this
  |
  = note: expected type `f64`
             found enum `Option<f64>`
help: consider using `Option::expect` to unwrap the `Option<f64>` value, panicking if the value is an `Option::None`
  |
9 |     let d: f64 = discount(code).expect("REASON");
  |                                +++++++++++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `coupon` (bin "coupon") due to 1 previous error

Read it like a sentence:

  • error[E0308]: mismatched types: you used one type where a different one was needed. E0308 is the error's ID; you can look it up any time.
  • --> src/main.rs:9:18: file, line 9, column 18.
  • expected `f64`, found `Option<f64>` : you promised d is a plain number (f64), but discount gives back "maybe a number" (Option<f64>). The compiler will not let you pretend the "maybe" isn't there.
  • help: consider using `Option::expect` : the compiler even offers a fix. But notice what expect does: it crashes the program if the value is None. That is the Python behaviour again, just on purpose. The compiler can't know what an unknown coupon should mean for your shop. That decision is yours.

For our shop, an unknown code means no discount. unwrap_or(0.0) says exactly that: use the number inside, or 0.0 if there is none.

fn discount(code: &str) -> Option<f64> {
    match code {
        "EID10" => Some(0.10),
        _ => None, // unknown code: no discount
    }
}

fn final_price(price: f64, code: &str) -> f64 {
    let d = discount(code).unwrap_or(0.0); // no coupon means 0% off
    price - price * d
}

fn main() {
    println!("{}", final_price(500.0, "EID10"));
    println!("{}", final_price(500.0, "EID100"));
}
450
500

The bug was found and fixed before the program ever ran once. Notice that the fix is also documentation: anyone reading unwrap_or(0.0) knows what happens with a bad code.

Under the hood

What exactly does the compiler check that other languages leave for later? Four big families, and you will meet each one in this course:

  1. Types, including "maybe missing". Rust has no null. A value that can be absent is an Option, and the compiler makes you handle the None case. (This lesson.)
  2. Who owns each piece of memory. Every value has exactly one owner, and memory is freed when the owner is done. No garbage collector, and no "used after free". (Part 2)
  3. Who may change data right now. Many readers or one writer, never both at once. This one rule removes a whole class of bugs, including data races between threads. (Borrowing Rules)
  4. Every case handled. A match must cover every possibility. Forget one and it does not compile. (match)

The important part: these checks run at compile time only. The finished program does not carry them around. There is no garbage collector pausing your server and no hidden runtime checks for these rules. You pay once, while compiling, and the program runs at full speed.

The cost is real, though. For the first few weeks you will spend time reading compiler errors that would not exist in Python. That is the famous "learning curve". The trick this course uses is simple: every error gets read in plain words, so the errors teach you instead of blocking you.

Compared with other languages

The same "unknown coupon" mistake, in four languages. Go deserves a look too: a missing map key gives the zero value, so it returns 0 without any error.

package main

import "fmt"

var coupons = map[string]float64{"EID10": 0.10}

func finalPrice(price float64, code string) float64 {
	return price - price*coupons[code] // unknown code gives 0, silently
}

func main() {
	fmt.Println(finalPrice(500, "EID10"))
	fmt.Println(finalPrice(500, "EID100"))
}
450
500

Go printed the right answer here, but only by luck. If the same lookup were prices[item] for a product that does not exist, the zero value would be a price of ৳0, and the shop would happily sell it for free.

LanguageWrong coupon EID100When you find out
PythonTypeError crashwhen that line runs, maybe in production
JavaScriptNaN, keeps goingmaybe never, maybe from a customer
Go0, keeps goingcorrect by luck here, silent when it isn't
Rustdoes not compile until you decidebefore the program exists

None of this makes Python, JavaScript or Go bad languages; they made different trade-offs, mostly for speed of writing. Rust trades a bit of writing speed for finding mistakes earlier and running faster.

Key takeaway

Rust is not harder, it is earlier. It moves whole families of bugs (missing values, memory mistakes, data races, forgotten cases) from 3 AM in production to compile time at your desk. The compiler's errors are the price, and they are also the teacher. The rest of this course is about learning to read them.

Practice

Objective: use Option so the compiler makes you handle a missing value.

Challenge: write stock(item: &str) -> Option<u32> that knows two items: rice has 12 left, oil has 0. Anything else is None. Then write can_sell(item: &str) -> String that returns one of three messages: how many are left, out of stock, or not sold in this shop. Print the message for rice, oil and sugar.

Expected result:

rice: 12 left, you can sell it
oil: out of stock
sugar: not in our shop
Hint 1

match item { "rice" => Some(12), "oil" => Some(0), _ => None } gives you stock.

Hint 2

In can_sell, match stock(item) and handle Some(0), Some(n) and None. The order matters: put Some(0) before Some(n).

Hint 3

format!("{item}: {n} left, you can sell it") builds a String the same way println! prints one.

Solution
fn stock(item: &str) -> Option<u32> {
    match item {
        "rice" => Some(12),
        "oil" => Some(0),
        _ => None, // we don't sell this item
    }
}

fn can_sell(item: &str) -> String {
    match stock(item) {
        Some(0) => format!("{item}: out of stock"),
        Some(n) => format!("{item}: {n} left, you can sell it"),
        None => format!("{item}: not in our shop"),
    }
}

fn main() {
    for item in ["rice", "oil", "sugar"] {
        println!("{}", can_sell(item));
    }
}

Try deleting the None => ... line and run cargo run. The compiler refuses with error[E0004]: non-exhaustive patterns: `None` not covered: it noticed you forgot the "not in our shop" case. That is the strict senior again, this time catching a missing case instead of a missing value.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →