Fix a function that returns &'static str built from a String (E0515)
status_text turns a status code into a label. At first it returned only fixed labels, so its return type became &'static str. Then a default arm that builds the label at run time was added, and the code stopped compiling: error[E0515]: cannot return reference to local variable `text` . Explain why the 'static promise cannot hold here, and fix the function.
Requirements:
- The program prints
OK,Not FoundandUnknown (503), one per line. - Any code without a fixed label gets
Unknown (<code>). - No
unsafeand noBox::leak.
fn status_text(code: u16) -> &'static str {
match code {
200 => "OK",
404 => "Not Found",
_ => {
let text = format!("Unknown ({code})");
&text
}
}
}
fn main() {
for code in [200, 404, 503] {
println!("{}", status_text(code));
}
}Find and fix the bug.
&'static str promises data valid until the program ends. Literals like "OK" qualify, but text is a local String freed on return, so &text would dangle (E0515). Return an owned String or a Cow<'static, str>.
- Thinking a
'staticannotation makes a local value live longer - Dropping
'staticfor-> &str, which fails with E0106: there is no input to borrow from - Returning
text.as_str(), which still borrows the localString
- Why does a string literal such as
"OK"have the type&'static str? - When is the clone-on-write type
Cow<'static, str>worth it over a plainString?
&'static str is a reference to data that is not freed until the program ends. String literals qualify: their bytes live in the executable, so "OK" and "Not Found" have the type &'static str. But text is created on every call and freed when the function returns. The 'static annotation does not extend its life; it only demands something that is not there, and the compiler refuses &text.
use std::borrow::Cow;
// an owned string: the caller gets the data, not a reference
fn status_text(code: u16) -> String {
match code {
200 => "OK".to_string(),
404 => "Not Found".to_string(),
_ => format!("Unknown ({code})"),
}
}
// Cow: literals are handed out as they are, a string is built only in the default arm
fn status_text_cow(code: u16) -> Cow<'static, str> {
match code {
200 => Cow::Borrowed("OK"),
404 => Cow::Borrowed("Not Found"),
_ => Cow::Owned(format!("Unknown ({code})")),
}
}
fn main() {
for code in [200, 404, 503] {
println!("{} | {}", status_text(code), status_text_cow(code));
}
}The output is OK | OK, Not Found | Not Found, Unknown (503) | Unknown (503). String is the simple and sufficient fix: every call allocates, but the caller is tied to nothing. Cow<'static, str> allocates only for unknown codes and prints and compares just like a string. Removing 'static and writing -> &str does not work: there are no input references, and the compiler answers with E0106. Box::leak technically yields a &'static str, but leaves a new string in memory on every call.