Step 5 of 7
'static: references that live forever
One lifetime name is built in: 'static, meaning "valid for the entire run of the program". Every string literal is a &'static str. Its bytes are stored inside the compiled program itself, so they're never freed.
fn level_name(code: u8) -> &'static str {
match code {
0 => "debug",
1 => "info",
2 => "warn",
_ => "error",
}
}
const APP: &str = "RustArena";
fn main() {
let name;
{
let code = 2;
name = level_name(code);
}
println!("{APP}: {name}");
}
RustArena: warn
level_nametakes no references, so elision has nothing to borrow from:-> &stralone would be E0106. The result is always a literal, so&'static stris the honest answer, and the caller can keep it as long as it likes.- Constants and statics are always
'static, soconst APP: &strdoesn't need the annotation. - A struct field can also be
&'static strwith no lifetime parameter on the struct:struct HttpError { code: u16, reason: &'static str }. That's common for fixed messages and lookup tables.
Common mistakes
- Adding
'staticto make an error go away. When the compiler complains about lifetimes, it's tempting. It never works for data created while the program runs, because that data really is dropped:
fn make_label(id: u32) -> &'static str {
let s = format!("ticket-{id}");
&s
}
fn main() {
println!("{}", make_label(7));
}
error[E0515]: cannot return reference to local variable `s`
s is a String built at run time and dropped at the end of make_label. The real fix, returning a String, is the next step. Read the help on E0106 carefully too: it suggests 'static, but adds "this is uncommon unless you're returning a borrowed value from a const or a static".
- Reading
T: 'staticas "lives forever". You'll meet'staticas a bound on a type, for example instd::thread::spawn.T: 'staticmeans "contains no borrowed references that could expire". Every owned type qualifies:String,Vec<u32>,i32, your structs without references. The threads module explains why spawn needs it.
Your task
Write status_text, which turns an HTTP status code into its reason phrase: 200 is OK, 404 is Not Found, 500 is Internal Server Error, anything else Unknown. Fix the return type so it compiles.
Challenge 2
Fill in the blank so HttpError can hold a fixed message without a lifetime parameter. The program prints 404 Not Found.
Challenge 3
Leaderboards print places as 1st, 2nd, 3rd, 4th... Write fn suffix(n: u32) -> &'static str and fn ordinal(n: u32) -> String.
The rule: numbers ending in 11, 12 or 13 always use th (11th, 112th). Otherwise a last digit of 1 is st, 2 is nd, 3 is rd, and everything else is th.
Previous: Structs that hold references Next: When to return owned data instead