Format! with non literal string



I recently had some headache trying to work around format!, who only accepts string literals as first argument.

Basically, my use case is something like that:

fn message(language: &str, name: &str, number: i32) -> String { 
    let s = match language {
        "french" => "Bonjour {}, le nombre est {}",
        "spanish" => "Hola {}, el numero es {}",
        _ => "Hi {}, the number is {}"
    format!(s, name, number) //doesn't work: first argument to format! must be a string literal

The documentation I found explains quite clearly why the first argument to format! must be a string literal, but I found it less clear what you are supposed if you can’t have one. Is there an equivalent of format! that checks the format string at runtime instead of compilation?

Thanks ! :smile:


There’s an (unstable) API for the parser used here.

I’ve used it before here, which might give some hints.


I just use str::replace, since there isn’t anything better right now.


There’s a variety of templating libraries, although they may be unnecessarily heavy for your purpose.


Thanks for the answers! I guess I will probably move to a templating library in the future; for now, using replace, provides a quick fix. :slight_smile: