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.
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}");
}
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.
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.
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! π