结论:'static 表示"活到整个程序结束"的生命周期,有两种常见用法:①引用类型 &'static str——指向的数据整个程序期间有效(如字符串字面量、static 变量);②trait bound T: 'static——类型 T 不包含任何非 'static 的引用(要么拥有全部数据,要么只含 'static 引用)。
展开:字符串字面量存于程序二进制中,天然是 &'static str;Box::leak 泄漏的堆数据也能获得 &'static mut。T: 'static 常见于 thread::spawn 和 trait object(Box<dyn Trait> 默认 + 'static):它要求值"可以"安全存活任意久,从而能跨线程或装箱存放——注意是"可以",并不强制它真的活到程序结束。易错点:新手常用 Box::leak 强行制造 'static 来绕过借用问题,这会永久泄漏内存,多数情况应重构所有权或改用 Arc。追问方向:如何向线程传入非 'static 的借用数据?用作用域线程 std::thread::scope,它在编译期保证线程先于借用数据结束。
let s: &'static str = "literal";
std::thread::scope(|scope| {
let local = 1;
scope.spawn(|| println!("{local}")); // 借用栈数据,无需 'static
});