lifetime.md (2722B)
1 # Lifetime 2 3 # static 4 5 ### Question: Whats the difference between 'static reference and 'static trait bound? 6 7 The two uses of 'static in Rust look similar but mean very different things: 8 9 - ``&'static T` — A Static Reference: 10 11 A &'static T is a reference that lives for the entire duration of the program. 12 The data it points to must be stored somewhere that never gets freed — typically 13 in the binary itself (e.g., string literals) or in a static variable. 14 [rust-lang](https://internals.rust-lang.org/t/idea-aliasing-the-static-lifetime-for-lifetime-parameters-trait-bounds-e-g-auto/19117) 15 16 ```rust 17 let s: &'static str = "hello world"; // baked into the binary 18 ``` 19 20 The key constraint here is on the reference itself: the pointed-to data must 21 outlive everything. 22 [rust-lang](https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html) 23 24 - `T: 'static` — A Static Trait Bound: 25 26 A T: 'static bound does not mean T is a reference at all. It means the type T 27 contains no non-static references — i.e., T holds no borrowed data that could 28 expire. 29 30 ```rust 31 fn generic<T: 'static>(x: T) { ... } 32 ``` 33 34 Crucially, any fully owned type (like String, Vec<i32>, u32) automatically 35 satisfies T: 'static, because it has no internal borrowed references that could 36 go stale. A &'static str also satisfies it, but a &'a str (with a non-static 37 lifetime) does not. 38 [rust-lang](https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html) 39 40 > It is a common misconception that 'static always means "lives forever", but 41 > this is not the case. Just because a value is 'static does not mean that you 42 > have a memory leak. You can read more in 43 > [Common Rust Lifetime Misconceptions](https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#2-if-t-static-then-t-must-be-valid-for-the-entire-program). 44 45 ### Question: When `T: 'static` Is Needed? 46 47 The T: 'static bound is commonly required when values must escape their creation 48 scope, such as when spawning threads with thread::spawn. Since a spawned thread 49 can outlive the caller, Rust requires that anything sent into it contains no 50 short-lived references — which is exactly what T: 'static guarantees. 51 [Rust Traits are not interfaces](https://www.jamessturtevant.com/posts/rust-traits-are-not-interfaces-and-a-little-on-lifetimes/), 52 [Learning Rust: static trait bounds](https://codeandbitters.com/static-trait-bound/) 53 54 ```rust 55 // thread::spawn requires T: Send + 'static 56 fn run_in_background<T: Send + 'static>(val: T) { 57 std::thread::spawn(move || { /* use val */ }); 58 } 59 ``` 60 61 A useful mental shortcut: &'static T is about where data lives; T: 'static is 62 about whether a type is safe to keep indefinitely.