Vec leak Into Static Slice
Convert an owned Vec into a static-lifetime slice with Vec::leak, trading the deallocation path for data that lives for the whole program.
Code
use std::thread;
fn main() {
// 构造一份启动期数据:只在初始化时分配一次
let table: Vec<u32> = (0..8).map(|i| i * i).collect();
// Vec::leak 消费 Vec,把元素留在原地,返回 &'static [u32]
// 代价:内存永不释放——适合进程生命周期内活着的查找表
let leaked: &'static [u32] = table.leak();
println!("leaked: {leaked:?} len {}", leaked.len());
// 'static 切片可以移进任何线程,无需 Arc
let worker = thread::spawn(move || leaked.iter().sum::<u32>());
println!("sum from thread: {}", worker.join().unwrap());
// &mut 切片也能 leak:构建后冻结为只读静态数据
let mut config: Vec<String> = vec!["mode=fast".into(), "retries=3".into()];
let frozen: &'static [String] = config.leak();
for line in frozen {
println!("cfg: {line}");
}
// 原来的 Vec 已经让渡所有权:table 在此行之后不可再使用(编译期强制)
}Leaking into static lifetime
The main function stages each leak scenario in sequence.
Repetition is confined to for line in frozen — the rest of the file is straight-line.
What to watch for
- std::thread is the sole import; the rest is Vec and slice methods.
Applying it
The entry-point signature is fn main()
The run prints leaked:, sum from thread:, cfg: — each prefix names the step that produced it.
The leak call sites
let worker = thread::spawn(move || leaked.iter().sum::<u32>());
let table: Vec<u32> = (0..8).map(|i| i * i).collect();
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does Vec leak Into Static Slice print when run?
- Run it as a complete program — the output lines carry labels such as `leaked:`, `sum from thread:`, `cfg:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.