#string #runtime #format #template

formatx

A macro for formatting non literal strings at runtime

8 releases

0.2.2 Dec 3, 2023
0.2.1 Feb 3, 2023
0.2.0 Dec 6, 2022
0.1.4 Aug 15, 2022

#206 in Rust patterns

Download history 1069/week @ 2023-11-06 1530/week @ 2023-11-13 1134/week @ 2023-11-20 1583/week @ 2023-11-27 2218/week @ 2023-12-04 2671/week @ 2023-12-11 3462/week @ 2023-12-18 736/week @ 2023-12-25 566/week @ 2024-01-01 880/week @ 2024-01-08 1346/week @ 2024-01-15 2181/week @ 2024-01-22 2159/week @ 2024-01-29 1092/week @ 2024-02-05 1558/week @ 2024-02-12 888/week @ 2024-02-19

5,834 downloads per month
Used in 7 crates (2 directly)

MIT/Apache

39KB
829 lines

formatx

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

formatx is a dependency free string templating library with syntax derived from std::fmt. formatx exports formatx! macro which is similar to format! macro. formatx works by first parsing the template string and then it uses format! macro internally to replicate it's behaviour. formatx aims for formatting strings and numbers although an generic type can also be formatted like an struct.

Getting Started

Add this to your Cargo.toml file.

[dependencies]
formatx = "0.2.2"

Or add from command line.

$ cargo add formatx

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

Warning 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();
  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