Crates.io | formatx |
lib.rs | formatx |
version | 0.2.2 |
source | src |
created_at | 2022-08-03 07:38:56.775453 |
updated_at | 2023-12-03 12:57:25.089187 |
description | A macro for formatting non literal strings at runtime |
homepage | |
repository | https://github.com/clitic/formatx |
max_upload_size | |
id | 637894 |
size | 54,412 |
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.
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.
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
Warning Examples given below will always panic.
Only types which implements Display + Debug traits are supported. Other formatting-traits aren't supported.
Local variable interpolation isn't supported.
let people = "Rustaceans";
formatx!("Hello {people}!").unwrap();
formatx!("{1} {} {0} {}", 1, 2).unwrap();
$
sign argument isn't supported.formatx!("{:width$}!", "x", width = 5).unwrap();
.*
can't be used to set precision.formatx!("{:.*}", 5, 0.01).unwrap();
Dual Licensed