Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
WebAssembly with Rust: wasm-pack, wasm-bindgen, JS interop, performance optimization and deployment. From Rust code to a running Wasm binary in the browser.
Rust's type and borrow checker catch whole bug classes at compile time. But some things cannot be checked automatically. An unsafe feature is one that imposes a contract: rules that Rust cannot enforce itself but that you must follow to avoid undefined behavior (UB).
Undefined behavior is behavior Rust assumes will never happen. If it does, Rust makes no predictions about the consequences — from confusing crashes to handing control of your computer to an attacker.
Example: a raw pointer advanced beyond the end of its original referent violates the pointer contract. Rust still compiles it — the safety check does not catch it. You bear the responsibility.
These options become available inside unsafe:
unsafe functionsunionsstatic variablesA contract goes beyond type checks
A contract is rules in addition to the usual type and lifetime checks. Rust usually doesn't even know about it; it's only in the docs of the unsafe feature. If you violate it, you break your side of the deal with Rust, and Rust declines to predict the consequences.
Why Rust's safety model is scientifically grounded
Rust's borrow checker prevents at compile time exactly the error classes that lead to the most common security vulnerabilities in C/C++: null dereference, use-after-free, and double-free. Current research confirms this:
#![forbid(unsafe_code)] — a crate audit layer that deterministically
aggregates safety signals.unsafe is the conscious exit from this safety model — use it sparingly and
always with a // SAFETY: comment.
Check: What does Undefined Behavior (UB) mean in Rust?
Answer: Behavior Rust assumes will never happen — consequences are unpredictable
UB is behavior Rust assumes is impossible. If it happens, there are no guarantees — from crashes to security holes. It is not caught at compile time.
⚠ Common mistake: An
unsafeblock does not switch off the borrow checker — two simultaneous&mutreferences to the same variable remain a compile error inside it. unsafe unlocks only the five extra operations; every ordinary rule still applies. If you need aliasing, you must go through raw pointers — and then the responsibility is yours.
Takeaways:
An unsafe block looks like a normal block preceded by unsafe. Inside, you
may use unsafe features — e.g. String::from_utf8_unchecked:
fn main() {
let ascii = b"hello".to_vec();
// from_utf8_unchecked is an unsafe function:
let s = unsafe { String::from_utf8_unchecked(ascii) };
println!("{s}");
// → hello
}
Without unsafe Rust rejects the call. The block segregates code that
deserves special scrutiny from the rest of the program.
An unsafe fn is a function with a contract:
/// Returns a String without a runtime UTF-8 check.
///
/// # Safety
/// `bytes` must contain valid UTF-8.
unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
String::from_utf8_unchecked(bytes)
}
Calling it requires an unsafe block. The # Safety docs explain the contract.
Block vs. function — two messages
unsafe fn = "I'm providing a dangerous tool." → docs should have # Safety.unsafe block = "I'm using dangerous tools." → ideally with a
// SAFETY: comment explaining why the use is correct.Even inside an unsafe fn, it makes sense to wrap unsafe code in an unsafe
block. Rust warns otherwise; with #![deny(unsafe_op_in_unsafe_fn)] that
becomes an error.
Check: What does 'unsafe fn' mark a function as?
Answer: Its correct use requires additional rules (a contract)
Unsafe fn means: there is a contract. Wrong use can cause UB. The body itself need not use unsafe features.
⚠ Common mistake: Calling an
unsafe fnwithout a surroundingunsafeblock yieldserror[E0137]: call to unsafe function is unsafe and requires an unsafe function block— and since Edition 2024 that also holds inside the body of your ownunsafe fn. The keyword on your own function is no substitute for the block; the block marks exactly the lines that deserve extra scrutiny.
Takeaways:
A raw pointer is an unconstrained pointer — like a C pointer. You can build
structures checked pointers don't allow (e.g. doubly linked lists). But Rust
can't tell whether you use it safely, so you may only dereference it inside an
unsafe block.
*mut T — a raw pointer that may modify its referent*const T — a raw pointer that may only read its referentThere is no *T — you must specify const or mut.
fn main() {
let mut x = 10;
let ptr_x: *mut i32 = &raw mut x; // the &raw-mut operator
let y = Box::new(20);
let ptr_y: *const i32 = &*y; // implicit coercion
unsafe {
*ptr_x += *ptr_y; // dereference only here
}
assert_eq!(x, 30);
}
Raw pointers may be null (like C NULL) and are not automatically
dropped/freed.
Conversion in only one direction
References coerce implicitly to raw pointers — but not the other way around.
You turn a raw pointer into a reference only with an explicit &*ptr (or
&mut *ptr), and only after checking that the pointer is valid and not null.
Check: Where may you dereference a raw pointer?
Answer: Only in an unsafe block
Because Rust can't check whether raw pointers are safe, dereferencing is only allowed inside an unsafe block.
⚠ Common mistake: Raw pointers carry no lifetime:
let p: *const i32 = &*y;followed bydrop(y)compiles without a single warning — dereferencingpafterwards is use-after-free. The compiler can't see it because raw pointers forget where they came from; a reference's lifetime would have prevented it.
Takeaways:
An optimizer transforms your program step by step — faster, smaller. It relies on some things never happening (UB). This assumption permits aggressive optimization.
Example — the compiler may assume:
let i = 10;
some_function(&i);
println!("{}", i * 100);
If some_function contains unsafe code that mutates i through the pointer,
contradicting its reference semantics, that is UB. The compiler may then
compute the result of i * 100 in advance, as if i were unchanged — and
the program surprises you.
Most bugs are harmless until they're not
UB is not always visible. Sometimes it has no visible effect, sometimes it crashes, sometimes it opens a security hole — and it may change between Rust versions without warning. The consequences of UB are nowhere guaranteed.
Check: Why does Rust allow so much optimization despite UB risk?
Answer: Because the compiler assumes UB never happens — this enables efficient code
The compiler draws boundaries around what it expects. Assuming UB never happens allows aggressive optimization. If UB does happen, the consequences are undefined.
⚠ Common mistake: "Works on my machine" proves nothing: a contract violation can happen to produce the right result in a debug build, then compute differently or crash in the optimized release build. Tests don't reliably surface UB — only upholding the contracts themselves is.
Takeaways:
Just like functions, traits can be unsafe. Marking a trait unsafe
signals: whoever implements it must uphold certain guarantees. Send and
Sync are classic unsafe traits.
unsafe trait MyContract {
fn do_it(&self);
}
// Only unsafe code may implement it:
unsafe impl MyContract for MyType { ... }
Only unsafe code may implement an unsafe trait — because the implementation
carries a contract.
Raw pointers may be null. Develop conventions to handle this safely:
fn option_to_raw<T>(opt: Option<&T>) -> *const T {
match opt {
Some(r) => r as *const T,
None => std::ptr::null(),
}
}
fn raw_to_option<'a, T>(raw: *const T) -> Option<&'a T> {
if raw.is_null() {
None
} else {
Some(unsafe { &*raw })
}
}
std::ptr::null() / null_mut() create null pointers.is_null() checks for null&*raw: make sure it's not null and validNormal references are never null
In safe Rust you can never have a null reference — that's guaranteed. Only raw pointers know null. That's exactly why converting pointer↔reference is an unsafe area: you must handle the null check yourself.
Check: May raw pointers in Rust be null?
Answer: Yes, like NULL in C — so they must be checked before dereferencing
Raw pointers may be null (like C NULL). References never are. That's why converting pointer↔reference is unsafe — you must check for null.
⚠ Common mistake: A careless
unsafe impl Sendfor a type holding anRccompiles without complaint — nobody checks the "safe to send across threads" guarantee. What waits at runtime is a data race, becauseRcworks without atomic counters. Manually implementingSendorSyncmeans giving a guarantee the type may not actually hold.
Takeaways:
The compiler knows the size and alignment of every type. Raw pointers have methods that count in units (not bytes):
use std::mem;
let arr = [1u8, 2, 3, 4];
let ptr = arr.as_ptr();
// Move n elements forward (in T-units, here bytes):
let third = unsafe { *ptr.add(2) };
assert_eq!(third, 3);
println!("usize: {}", mem::size_of::<usize>());
// → usize: 8
.add(n) moves by n elements (type-based), .offset(n) similarsize_of::<T>() / align_of::<T>() give size/alignmentA union is a struct type from C whose fields all live at the same memory
location:
union UnspecifiedShape {
circle: u32,
rectangle: u32,
}
Unlike an enum, a union carries no tag indicating which field is
initialized. That's why reading from a union field is unsafe — only
writing is safe. You use unions almost exclusively for FFI / C compatibility.
How does enum differ from union?
An enum has a tag that records which variant is present — the compiler
knows. A union has no such tag: all fields lie at the same offset, and
there's no information about which is valid. Hence reading from a union is
unsafe unless you know the active value.
Check: Why is reading from a union field unsafe?
Answer: Because a union has no tag telling which field is initialized
Unlike an enum, a union has no tag. All fields share the same memory; the compiler can't ensure the read bit pattern is valid for the type.
⚠ Common mistake:
.add(n)counts elements, not bytes: on a*const u32,add(4)moves the pointer 16 bytes ahead. Thinking in bytes, you read past the end of the array — instant UB, often with no visible effect. For true byte steps there is.byte_add(n).
Takeaways:
The core trick of good unsafe: hide small amounts of unsafe behind safe interfaces so the rest of the program stays safe. Your task:
Vec<u8> (known valid UTF-8) into a String
with String::from_utf8_unchecked — as an unsafe fn with # Safety docs.main from an unsafe block, with a // SAFETY: comment.i32, mutate the value through the pointer in the
unsafe block, and show the original variable changed.// SAFETY: comment that explains EXACTLY why your code does not
violate the contract.This exercises: unsafe functions, unsafe blocks, raw pointers, and the mindset — taking responsibility for contracts — that this module teaches.
Recipes from this module
unsafe fn ... + # Safety docsunsafe { ... } + // SAFETY: why correct&raw mut x or coercion &*x.add(n)/.offset(n) in type units, within boundariesScenario: The sensor library
⚠ Common mistake: A wrapper that feeds unchecked input to
String::from_utf8_uncheckedis only apparently safe: the safe signature promises harmlessness, but UB is created inside the moment the bytes aren't valid UTF-8. The invariant must genuinely be checked before theunsafeblock — or simply use the safe counterpartString::from_utf8.
Takeaways:
Course navigation: ← Module 19 · All 27 modules · Module 21 →