Expand description
§Lifetimes - Rust Book Chapter 10.3
This module demonstrates lifetime annotations from The Rust Book Chapter 10.3.
§Key Concepts Demonstrated
-
Lifetime Parameters on Structs (Chapter 10.3)
CallGraphBuilder<'a>holds references with lifetime'a- Prevents the struct from outliving its referenced data
- Zero-cost abstraction - no runtime overhead
-
Why Lifetimes Matter
- Prevent dangling references at compile time
- Enable borrowing without ownership transfer
- Alternative to heap allocation (
Box) or reference counting (Rc)
-
When You Need Explicit Lifetimes
- Structs that store references
- Functions returning references
- Multiple references with different lifetimes
§Learning Notes
Most code doesn’t need explicit lifetimes!
- Rust has “lifetime elision” rules that infer lifetimes
- You only write lifetimes when Rust can’t figure them out
- This module is a good example of when they’re necessary
The lifetime syntax:
'a- A lifetime parameter (can be any name:'b,'lifetime, etc.)&'a T- A reference toTthat lives for lifetime'a&'a mut T- A mutable reference toTthat lives for lifetime'a
Common lifetime names:
'a,'b,'c- Generic lifetime parameters'static- Special lifetime for the entire program duration
Structs§
- Call
Graph Builder - Builds a call graph by recursively tracing function calls.
- Call
Node - A node in the call graph tree
- Call
Tree - Represents a complete call graph tree
Enums§
- Trace
Direction - Direction of the call graph trace