RustArena

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

Common mistakes

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".

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