#string #runtime #format #template

formatx

A macro for formatting non literal strings at runtime in Rust

5 releases

Uses new Rust 2021

new 0.1.4 Aug 15, 2022
0.1.3 Aug 5, 2022
0.1.2 Aug 5, 2022
0.1.1 Aug 5, 2022
0.1.0 Aug 3, 2022

#310 in Rust patterns

Download history 75/week @ 2022-07-31 36/week @ 2022-08-07

111 downloads per month

MIT/Apache

40KB
862 lines

formatx

A macro for formatting non literal strings at runtime in Rust.

This library aims for formatting strings and numbers rather than an generic type. Syntax for the format string is derived from std::fmt.

Getting Started

Add this to your Cargo.toml file.

[dependencies]
formatx = "0.1"

Or add from command line.

$ cargo add formatx@0.1

See docs and examples to know how to use it.

Example

SOURCE: format! with non literal string

use formatx::formatx;

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 {}",
    };
    formatx!(s, name, number).unwrap()
}

fn main() {
    println!("{}", message("french", "Léa", 1));
    println!("{}", message("spanish", "Sofia", 2));
    println!("{}", message("english", "Ashley", 3));
}

OUTPUT

Bonjour Léa, le nombre est 1
Hola Sofia, el numero es 2
Hi Ashley, the number is 3

Limitations

Examples given below will always panic.

  1. Only types which implements Display + Debug traits are supported. Other formatting-traits aren't supported.

  2. Local variable interpolation isn't supported.

let people = "Rustaceans";
formatx!("Hello {people}!").unwrap().text().unwrap();
  1. Intermingling the two types of positional specifiers isn't supported.
formatx!("{1} {} {0} {}", 1, 2).unwrap();
  1. Parameter setting through $ sign argument isn't supported.
formatx!("{:width$}!", "x", width = 5).unwrap();
  1. An asterisk .* can't be used to set precision.
formatx!("{:.*}", 5, 0.01).unwrap();

Alternatives

  1. strfmt
  2. runtime-fmt

License

Dual Licensed

No runtime deps