How do I make format! return a &str from a conditional expression?

This is 90% a duplicate of Return local String as a slice (&str), see that for multiple other solutions.

There’s one extra possibility since this is all in one function: You can declare a variable for the String and only set it when you need to allocate. The compiler (obliquely) suggests this:

consider using a let binding to create a longer lived value

fn main() {
    let x = 42;
    let tmp;

    let category = match x {
        0...9 => "Between 0 and 9",
        number @ 10 => {
            tmp = format!("It's a {}!", number);
            &tmp
        }
        _ if x < 0 => "Negative",
        _ => "Something else",
    };

    println!("{}", category);
}

This is mostly the same as using a Cow, just handled by the compiler instead of a specific type.

See also:

Leave a Comment