In this lesson, you will learn how to verify that your Rust lifetimes are purely conceptual and have been successfully erased during compilation.
When you write Rust code, the borrow checker enforces strict rules about lifetimes to ensure memory safety. However, once the compiler proves your code is safe, these lifetimes are "zero-cost." They shouldn't exist in the final machine code; they exist only as metadata for the compiler. To confirm this, we use assembly dumps.
How to Peek Under the Hood
To see what the compiler actually produces, you can use cargo-show-asm. When you run this on a function, you are looking for evidence that the "lifetime" constraints haven't introduced any runtime overhead (like extra branching or memory tracking).
Consider a simple function that returns a reference to a slice:
pub fn get_middle(data: &[i32]) -> &[i32] {
let len = data.len();
&data[1..len - 1]
}
Analyzing the Dump
If you run cargo asm on this, you will see assembly that performs basic pointer arithmetic (calculating the start address and length). What you won't see is any "lifetime object" or "scope check."
If the compiler has successfully performed lifetime erasure, the assembly for get_middle will look nearly identical to how you would write it in C. It should just be:
- An adjustment to the pointer (
addinstruction). - A subtraction from the length.
- A return of the pair (pointer + length).
If you see unexpected jumps or calls to library functions related to "checks" (beyond standard bounds checking), it means the compiler is still holding onto extra metadata or unable to prove the lifetime bounds statically.
By inspecting the assembly, you gain confidence that your high-level abstractions—like passing references with specific lifetimes—are being collapsed into raw, efficient memory offsets. You aren't paying a runtime tax for the borrow checker's peace of mind.
Key Takeaway: Lifetimes are a compile-time construct; use assembly inspection to confirm they have been erased and optimized into simple pointer arithmetic.