Skip to main content
Be Bitwise
RustWhat Your Rust Code Actually Does

Lifetimes Are Free

Lifetimes carry a reputation. The syntax — &'a str, <'a, 'b: 'a> — does its best to scare beginners off. The most useful thing to know upfront: lifetimes evaporate. Not a single CPU instruction goes toward checking them. This lesson nails that down by putting Rust assembly side-by-side with the equivalent C.

Lifetime Annotations Generate Zero Code

rust
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}

Compiled assembly:

asm
longest:
; rdi = a.ptr, rsi = a.len (str is a fat pointer)
; rdx = b.ptr, rcx = b.len
cmp rsi, rcx ; Compare lengths
mov rax, rdx ; Assume b
cmova rax, rdi ; If a.len > b.len, select a's pointer
cmova rcx, rsi ; And a's length
mov rdx, rcx ; Return: rax = ptr, rdx = len
ret

Now the equivalent C function:

c
struct str_slice { const char *ptr; size_t len; };
struct str_slice longest(struct str_slice a, struct str_slice b) {
if (a.len > b.len) return a;
return b;
}

Compiled assembly:

asm
longest:
; rdi = a.ptr, rsi = a.len
; rdx = b.ptr, rcx = b.len
cmp rsi, rcx
mov rax, rdx
cmova rax, rdi
cmova rcx, rsi
mov rdx, rcx
ret

Identical assembly. The 'a annotation contributes zero instructions. It exists for the borrow checker, full stop. By the time LLVM gets the IR, the named lifetimes have been thrown away. What survives is what the borrow checker proved: rustc marks reference parameters with LLVM attributes such as noalias, readonly, nonnull and dereferenceable, which are hints to the optimiser, not instructions. The restrict section below shows what noalias buys.

Borrowing vs Raw Pointers

rust
fn sum_slice(data: &[i32]) -> i32 {
data.iter().sum()
}
c
int sum_array(const int *data, size_t len) {
int total = 0;
for (size_t i = 0; i < len; i++) {
total += data[i];
}
return total;
}

Both compile to effectively the same loop:

asm
; Both versions (simplified):
xor eax, eax ; total = 0
.loop:
add eax, DWORD PTR [rdi]
add rdi, 4
dec rsi
jnz .loop
ret

The Rust version pins down four facts at compile time:

  • data points to valid memory
  • data is not null
  • Nothing else is mutating the data while we read it
  • The slice length is accurate

Not one of those checks survives into the binary. They're all settled before codegen even begins.

Mutable References: The Exclusivity Guarantee

rust
fn increment(value: &mut i32) {
*value += 1;
}
asm
increment:
add DWORD PTR [rdi], 1
ret

One instruction. The &mut borrow promises exclusive access — no other reference to this data exists, anywhere. With that promise in hand the compiler can generate code that doesn't have to second-guess itself about aliases.

In C, the matching void increment(int *value) { *value += 1; } produces the same assembly here, but the C compiler doesn't get the same promise. When it can't prove two pointers are independent, it conservatively reloads from memory.

The restrict Keyword Parallel

Rust's &mut exclusivity is the same idea as C's restrict, just enforced rather than assumed:

c
// C: programmer promises no aliasing (can lie!)
void add_arrays(int *restrict dst, const int *restrict src, size_t n) {
for (size_t i = 0; i < n; i++) dst[i] += src[i];
}
rust
// Rust: compiler PROVES no aliasing (cannot be wrong)
fn add_arrays(dst: &mut [i32], src: &[i32]) {
for (d, s) in dst.iter_mut().zip(src) {
*d += *s;
}
}

Zipping the two iterators stops at the shorter slice, so there's no dst[i] and no per-element bounds check in the way. In the LLVM IR (rustc 1.97, -C opt-level=2) the borrows turn into exactly the C promise:

text
define void @add_arrays(ptr noalias noundef nonnull align 4 %dst.0, i64 %dst.1,
ptr noalias noundef nonnull readonly align 4 %src.0, i64 %src.1)

Both generate vectorised SIMD loops. This is the core of rustc's x86-64 output, which handles 8 ints per iteration in two 4-int halves:

asm
; With no-aliasing guarantee, the compiler goes straight to SIMD:
movdqu xmm0, xmmword ptr [rdx + r8] ; Load 4 ints from src
movdqu xmm1, xmmword ptr [rdx + r8 + 16] ; ...and the next 4
movdqu xmm2, xmmword ptr [rdi + r8] ; Load 4 ints from dst
paddd xmm2, xmm0 ; Add them
movdqu xmm0, xmmword ptr [rdi + r8 + 16]
paddd xmm0, xmm1
movdqu xmmword ptr [rdi + r8], xmm2 ; Store 4 results
movdqu xmmword ptr [rdi + r8 + 16], xmm0

The loads go through movdqu because nothing promises 16-byte alignment, and SSE's paddd with a memory operand would fault on an unaligned address.

Strip away the no-alias guarantee (raw pointers in Rust, plain pointers in C) and the compiler can't assume dst and src are separate. LLVM still vectorises, but first it emits a runtime overlap check, comparing the two address ranges and falling back to a scalar loop if they touch. With restrict/&mut that check and the fallback go away. The catch with C restrict is that it's a promise the programmer can break, and breaking it lands you in undefined behaviour. Rust's borrow checker won't let you break it in the first place.

The smallest place to watch the promise pay off is a function that writes through two pointers and reads one back. This is real clang -O2 output for x86-64. Hover the return lines. Without restrict, the compiler has to reload *a, because b might point at the same int and the second store might have changed it. With restrict it knows the answer is still 1.

Aliasing with and without restrict

x86-64
C Source
1int store_two(int *a, int *b) {
2 *a = 1;
3 *b = 2;
4 return *a; /* b might be a */
5}
6
7int store_two_r(int *restrict a, int *restrict b) {
8 *a = 1;
9 *b = 2;
10 return *a; /* promised: b is not a */
11}
Assembly
1store_two:
2 mov dword ptr [rdi], 1
3 mov dword ptr [rsi], 2
4 mov eax, dword ptr [rdi] ; reload *a
5 ret
6
7store_two_r:
8 mov dword ptr [rdi], 1
9 mov dword ptr [rsi], 2
10 mov eax, 1 ; no reload
11 ret

Hover over code lines or mapping badges to see correspondences

Write the Rust version as fn store_two(a: &mut i32, b: &mut i32) -> i32 and rustc -O produces the second listing, mov eax, 1 included. Two &mut borrows can't overlap, so the compiler gets the restrict promise without anyone having to type it.

Unsafe Blocks: Same Assembly

rust
fn safe_access(slice: &[i32], index: usize) -> i32 {
slice[index] // Bounds-checked
}
fn unsafe_access(slice: &[i32], index: usize) -> i32 {
unsafe { *slice.get_unchecked(index) } // No bounds check
}
asm
safe_access:
; rdi = ptr, rsi = len, rdx = index
cmp rdx, rsi ; Bounds check
jae .panic ; If index >= len, panic
mov eax, DWORD PTR [rdi+rdx*4]
ret
.panic:
; Call panic handler (never returns)
unsafe_access:
; rdi = ptr, rsi = len, rdx = index
mov eax, DWORD PTR [rdi+rdx*4] ; Direct access, no check
ret

It's get_unchecked that strips out the bounds check, the cmp and jae. The unsafe block itself changes nothing in the assembly; it doesn't change the compilation pipeline, it just lets you call operations, like get_unchecked, that the compiler can't validate on your behalf.

The safe version's bounds check is one compare and one conditional jump. Modern CPUs predict it "not taken" with near-perfect accuracy. Outside of the hottest inner loops, it's invisible.

Lifetime Elision: Why You Often Do Not Write Lifetimes

rust
// You write this:
fn first_word(s: &str) -> &str {
&s[..s.find(' ').unwrap_or(s.len())]
}
// The compiler interprets it as:
fn first_word<'a>(s: &'a str) -> &'a str {
&s[..s.find(' ').unwrap_or(s.len())]
}

Lifetime elision rules let you skip annotations in the common shapes — the compiler fills them in. Either way, identical assembly. Lifetimes are gone long before codegen.

Comparing Rust to C: A Real Function

Here's a function you might actually write, in both languages:

rust
pub fn find_max(data: &[i32]) -> Option<&i32> {
if data.is_empty() {
return None;
}
let mut max = &data[0];
for item in &data[1..] {
if item > max {
max = item;
}
}
Some(max)
}
c
// C equivalent (returns NULL if empty)
const int *find_max(const int *data, size_t len) {
if (len == 0) return NULL;
const int *max = &data[0];
for (size_t i = 1; i < len; i++) {
if (data[i] > *max) max = &data[i];
}
return max;
}

Both compile to nearly identical assembly at -O2:

asm
; Both versions (simplified):
find_max:
test rsi, rsi
je .return_none
lea rax, [rdi] ; max = &data[0]
lea rcx, [rdi+4] ; i = &data[1]
lea rdx, [rdi+rsi*4] ; end = &data[len]
.loop:
cmp rcx, rdx
je .done
mov r8d, DWORD PTR [rcx]
cmp r8d, DWORD PTR [rax]
cmovg rax, rcx ; If *i > *max, max = i
add rcx, 4
jmp .loop
.done:
ret
.return_none:
xor eax, eax ; Return NULL/None
ret

The Rust signature returns Option<&i32> which, thanks to niche optimisation, is laid out as a nullable pointer — bit-for-bit equivalent to the C version's const int *.

What This All Means

Lifetimes, borrowing, the whole borrow-checker apparatus — it's all compile-time scaffolding. The output:

  • Zero runtime instructions for lifetime checking
  • Zero memory overhead for borrow tracking
  • Zero performance cost compared to equivalent C code

The borrow checker is a static analysis. Once it convinces itself your code is sound, it scrubs all evidence of itself from the compiler's intermediate state. The shipped binary doesn't know what a lifetime is.

This is Rust's pitch in three words: safety without overhead. The disassembly is the receipt. For the borrow checker's part, Rust and C emit the same machine code. Rust does keep some checks at run time: slice indexing is bounds-checked unless the optimiser can prove the index is in range, and debug builds check integer arithmetic for overflow. Those are separate from lifetimes, and they're how Rust turns into a panic what C would ship to production as a CVE.