⚑
World 20 Β· Advanced Magic & The Big Build

Advanced Magic (unsafe)

Almost everything you have learned in Rust comes with a built-in safety helper. Rust watches your back, checks your work, and stops scary mistakes before your program ever runs. But did you know there is one special, tiny doorway where Rust says, β€œOkay… I trust you. You’re on your own here”? It’s called unsafe. ⚑

What is unsafe?

Most of your Rust code is safe code. Safe code is like riding a bike with training wheels β€” you can wobble, but you won’t crash. Rust keeps you steady.

unsafe is a special block where you take the training wheels off for one tiny part of your ride. You can do a few risky things that Rust normally won’t allow, like using raw pointers (super-direct arrows to a spot in the computer’s memory). With great power comes great responsibility.

New word unsafe is a keyword that opens a small block where you promise Rust, "I really know what I'm doing here." Rust stops protecting that one little part.
Think of it like this… Imagine a locked toolbox high up on the shelf. Inside are sharp, powerful tools. Most of the time you don't need them at all. But once in a while, a careful expert opens the box, uses one tool very carefully, and locks it right back up. That's unsafe.

Who uses it, and when?

Honestly? Almost nobody, almost never. Most Rust programmers go a long, long time without writing a single unsafe block. It is used by experts building the deep, tricky parts that everything else stands on β€” like talking directly to the computer’s hardware.

Here is what a tiny unsafe block looks like. You don’t need to understand it β€” just notice the special word.

fn main() {
    let mut number = 5;
    let pointer = &mut number as *mut i32; // a raw pointer (a direct arrow!)

    unsafe {
        *pointer = 10; // only allowed inside unsafe
    }

    println!("number is now {number}");
}
Watch out! When you write unsafe, Rust stops checking that one part. If you make a mistake, your program can crash. That's why we leave it locked up unless we truly need it.
Ferris says: Rust has even more advanced features to discover down the road β€” like making your own iterators, powerful traits, and more. The journey never really ends! πŸ¦€

Quick quiz

What is unsafe in Rust?

Exactly! Almost all Rust is safe and protects you. unsafe is a small, locked toolbox you only open when you really, truly need it.

You learned… Nearly all Rust is safe and keeps you from crashing. unsafe is a tiny doorway for risky things like raw pointers, opened only by careful experts β€” like a locked toolbox. Now get ready for the grand finale: The Big Build: A Web Server! 🌐