Part 01 · Rust Is Not Scary

What Rust Is Good For

CLI toolsBackendsSystemsWebAssembly

Fast like C, safe like Go or Java, no garbage collector. Where Rust shines, and where another language is the better pick.

⏱ 9 min · Station 3 of 75

The story

A carpenter does not ask "which tool is the best?". A hammer is great for nails and terrible for screws. The good question is "which tool for this job?".

Programming languages are the same. Python is a fast way to write a script. JavaScript runs in every browser. Go makes simple network services easy. Rust has its own sweet spot: programs that must be fast, use little memory, and must not crash, often all three at once. This lesson shows what that means with real numbers, and where you should pick something else.

The idea

Rust gives you three things that usually don't come together:

  1. Speed like C and C++. Rust compiles to machine code, the same kind of program C produces. No interpreter reading your code line by line while it runs.
  2. Safety like Go or Java. No crashes from memory freed too early, no reading past the end of a list, no null. In Go and Java a garbage collector gives you that safety while the program runs. Rust gets it from the compiler's checks, before the program runs.
  3. No garbage collector. Memory is freed at a point you can see in the code, so there are no surprise pauses and memory use stays small and predictable.

That combination is why you find Rust in these places:

  • Command line tools: ripgrep (fast search), fd, bat, and the uv Python package manager are written in Rust. They start instantly and ship as one file.
  • Backends and infrastructure: services where every millisecond or megabyte costs money, such as proxies, databases, and queues. Cloudflare, Discord and AWS have all written about moving hot paths to Rust.
  • Systems code: parts of the Linux kernel, Windows, and Android now accept Rust, because memory bugs there are security bugs.
  • WebAssembly: Rust compiles to code that runs in the browser at near native speed.

Try it: add up two million orders

Our shop exported two million orders to orders.csv (28 MB, one order_id,amount_paisa per line). The job: count them and add up the money. First in Python:

total = 0
count = 0
with open("orders.csv") as f:
    next(f)  # skip the header line
    for line in f:
        _, amount = line.split(",")
        total += int(amount)
        count += 1
print(f"{count} orders, total {total / 100:.2f} taka")

The same job in Rust. Don't worry about every line yet; by the end of Part 1 you will read all of it. It reads one line at a time, exactly like the Python version:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let file = File::open("../orders.csv").expect("could not open orders.csv");
    let mut total: u64 = 0;
    let mut count: u64 = 0;
    // read one line at a time, like the Python version, and skip the header
    for line in BufReader::new(file).lines().skip(1) {
        let line = line.expect("could not read a line");
        let amount = line.split(',').nth(1).expect("missing amount");
        total += amount.parse::<u64>().expect("amount is not a number");
        count += 1;
    }
    println!("{count} orders, total {:.2} taka", total as f64 / 100.0);
}

Rust has two ways to build. cargo build makes a quick debug build for while you work. cargo build --release takes a bit longer and optimizes properly:

   Compiling total v0.1.0 (/home/you/rust-lab/total)
    Finished `release` profile [optimized] target(s) in 0.30s

Both versions give the same answer:

2000000 orders, total 5050288171.59 taka
2000000 orders, total 5050288171.59 taka
Predict first

Python takes about 0.9 seconds for this file. How long does the Rust release build take?

Three runs each, wall time and the most memory the program used (/usr/bin/time, on an Intel i3-10110U laptop, Ubuntu 26.04, Python 3.14, Rust 1.98):

python3 total.py         0.85 s  10236 KB
python3 total.py         0.93 s  10024 KB
python3 total.py         0.89 s  10204 KB

target/debug/total       0.87 s  2308 KB
target/debug/total       0.88 s  2336 KB
target/debug/total       0.89 s  2376 KB

target/release/total     0.17 s  2384 KB
target/release/total     0.17 s  2300 KB
target/release/total     0.16 s  2284 KB
TimeMax memory
Python~0.89 s~10 MB
Rust, debug build~0.88 s~2.3 MB
Rust, release build~0.17 s~2.4 MB

Reading the numbers:

  • The debug build is about as fast as Python. If someone tells you "Rust is slow", check whether they forgot --release. That is the most common beginner mistake in benchmarks.
  • The release build is about 5 times faster than Python for the same work.
  • Memory is about 4 times smaller in both Rust builds, because there is no interpreter and no garbage collector sitting in memory next to your program.

What the compiler says

Speed is nice, but the bigger reason companies choose Rust is the third word: safety, especially with threads. Imagine four checkout counters selling at the same time, all adding to one shared sold counter:

use std::thread;

fn main() {
    let mut sold = 0;
    let mut workers = Vec::new();
    for _ in 0..4 {
        // four checkout counters, each selling 1,000 items
        workers.push(thread::spawn(|| {
            for _ in 0..1000 {
                sold += 1;
            }
        }));
    }
    for w in workers {
        w.join().unwrap();
    }
    println!("sold {sold}");
}

This is a classic bug in many languages. Rust refuses to build it. The full message is long (you'll learn to read every part in Borrowing Rules and Arc and Mutex); here are just the headline lines:

error[E0373]: closure may outlive the current function, but it borrows `sold`, which is owned by the current function
error[E0499]: cannot borrow `sold` as mutable more than once at a time
error[E0502]: cannot borrow `sold` as immutable because it is also borrowed as mutable
error: could not compile `race` (bin "race") due to 3 previous errors

In plain words:

  • E0373: the threads might keep running after main is done with sold, so they cannot just borrow it.
  • E0499: four threads want to change sold at the same time. Rust allows many readers or one writer, never several writers at once.
  • E0502: main wants to read sold while the threads may still be changing it.

All three say the same thing from different angles: "these threads would step on each other". Why is that a real problem? Watch what happens when two counters do sold += 1 at the same moment:

soldcounter Acounter Bsold = 41sold = 42, should be 43read 41read 4141 + 1 = 4241 + 1 = 42write 42write 42two sales, but the count went up by oneRust will not compile this: error[E0499]
Two counters read 41 at the same moment, each adds one and writes 42. Two sales happened, but the count only went up by one. This is a data race, and Rust refuses to compile code that allows it.

Under the hood

Where do the speed and the small memory come from?

  • Compiled ahead of time. rustc turns your code into machine instructions for your CPU before it runs. Python's interpreter decides what each line means while it runs, every time.
  • The optimizer. --release turns on LLVM's optimizer (the same engine behind Clang, the C compiler). It inlines small functions, removes work that has no effect, and keeps values in CPU registers. That is the 0.88 s to 0.17 s jump.
  • No garbage collector. Memory is freed when its owner goes away (that's Part 2). Nothing scans memory in the background, and nothing pauses your program.
  • One file to ship. The release program is a single 485 KB file that needs only the system's C library. No runtime to install on the server, no node_modules, no virtualenv:
4.6M target/debug/total
485K target/release/total

The debug build is ten times bigger because it keeps debug information for debuggers. You ship the release build.

Compared with other languages

Here is the same four-counter program in Go, which does compile and run. Each counter sells 100,000 items, so the answer should be 400,000:

package main

import (
	"fmt"
	"sync"
)

func main() {
	sold := 0
	var wg sync.WaitGroup
	for c := 0; c < 4; c++ {
		// four checkout counters, each selling 100,000 items
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 100000; i++ {
				sold++
			}
		}()
	}
	wg.Wait()
	fmt.Println("sold", sold, "(expected 400000)")
}
sold 181000 (expected 400000)
sold 165615 (expected 400000)
sold 263748 (expected 400000)

Three runs, three different wrong answers, and no error. Most of the sales simply vanished, because counters kept overwriting each other's updates (the diagram above, thousands of times). Go has a race detector (go run -race) that catches this while the program runs, if your test happens to hit it. Rust catches it before the program exists.

So when should you pick Rust, and when not?

Pick Rust whenPick something else when
speed or memory cost real money (hot services, big data jobs)you need a quick script or a prototype by tomorrow (Python)
a crash is very expensive (payments, infrastructure, embedded)the team already knows Go or Java and the service is simple CRUD
you ship a CLI tool people installyou are building a browser UI (TypeScript)
you need threads without data racesyou need a huge ML ecosystem (Python)

A lot of real systems mix them: Python for the data science notebook, Go or Node for the simple API, Rust for the one piece that has to be very fast or very safe.

Key takeaway

Rust is for programs that need to be fast, small and reliable at the same time: CLI tools, performance-critical backends, systems code, WebAssembly. In our test it was about 5 times faster than Python with a quarter of the memory, but only in a --release build. And the compiler refused to build a data race that Go ran happily, losing half the sales. Use Rust where those things matter, and don't feel bad using another language where they don't.

Practice

Objective: change a real Rust program and build it in release mode.

Challenge: extend the order counter so it also prints the biggest single order in taka. Keep reading one line at a time.

Expected result:

2000000 orders, total 5050288171.59 taka
biggest order 5000.00 taka
Hint 1

Add let mut biggest: u64 = 0; next to total and count.

Hint 2

Inside the loop, parse the amount once into a variable (let amount: u64 = ...), then use it twice: add it to total, and compare it with biggest.

Hint 3

if amount > biggest { biggest = amount; } and print it at the end the same way as the total: biggest as f64 / 100.0.

Solution
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let file = File::open("../orders.csv").expect("could not open orders.csv");
    let mut total: u64 = 0;
    let mut count: u64 = 0;
    let mut biggest: u64 = 0;
    for line in BufReader::new(file).lines().skip(1) {
        let line = line.expect("could not read a line");
        let amount: u64 = line
            .split(',')
            .nth(1)
            .expect("missing amount")
            .parse()
            .expect("amount is not a number");
        total += amount;
        count += 1;
        if amount > biggest {
            biggest = amount;
        }
    }
    println!("{count} orders, total {:.2} taka", total as f64 / 100.0);
    println!("biggest order {:.2} taka", biggest as f64 / 100.0);
}

Run it with cargo run --release. Without --release it still works, just about 5 times slower.

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 →