295. String::leak — A &'static str From Runtime Data, Without the Box Detour
An API demands &'static str, but your string is built at runtime. The old trick was Box::leak(s.into_boxed_str()) — since 1.72, String::leak says what you mean.
You’ve built a name at startup and some API insists on &'static str:
| |
The value will live for the rest of the program — the borrow checker just can’t know that. The classic workaround was leaking through a Box (bite 67):
| |
String::leak (stable since 1.72) does it in one step, straight off the format!:
| |
It consumes the String and hands back a &'static mut str — mutable, exclusive, and alive until the process exits (it coerces to plain &'static str on the spot, as above):
| |
Two things to keep in mind. First, the allocation is never freed — that’s the point. Do this for once-per-process values (config, names, interned keys), never in a loop or per-request path. Second, unlike into_boxed_str, which shrinks the buffer to fit, leak leaks the whole allocation, spare capacity included. A String with 4 KB of capacity holding 10 bytes leaks 4 KB. If that matters, call shrink_to_fit() first.