formatx lets you format strings at runtime using the same syntax as std::fmt ({}, {:?}, {name}, etc.), but with runtime template strings instead of compile-time literals with zero dependencies.
Add this to your Cargo.toml file.
[dependencies]
formatx = "0.3"Or add from command line.
cargo add formatxSee docs and examples to know how to use it.
Using formatx!
Works just like format!, but accepts runtime template strings.
use formatx::formatx;
let template = "{} scored {score:.1}% in {}";
let result = formatx!(template, "Alice", "maths", score = 95.678).unwrap();
assert_eq!(result, "Alice scored 95.7% in maths");Note
Extra arguments that aren't referenced by any placeholder are silently ignored in both formatx! and formatxl!.
Parse once, render many times with Template.
use formatx::Template;
let template = Template::new("{name} has {n} items").unwrap();
let r1 = template.render()
.named("name", &"Alice")
.named("n", &3)
.finish()
.unwrap();
let r2 = template.render()
.named("name", &"Bob")
.named("n", &7)
.finish()
.unwrap();
assert_eq!(r1, "Alice has 3 items");
assert_eq!(r2, "Bob has 7 items");formatx supports most of the std::fmt formatting syntax:
| Feature | Example | Supported |
|---|---|---|
| Implicit positional | {} |
✅ |
| Explicit positional | {0} {1} |
✅ |
| Named arguments | {name} |
✅ |
| Mixed positional | {1} {} {0} {} |
✅ |
| Debug | {:?}, {:#?} |
✅ |
| Debug hex | {:x?}, {:X?} |
✅ |
| Width | {:10} |
✅ |
| Precision | {:.5} |
✅ |
| Fill and align | {:-<10}, {:^10}, {:*>10} |
✅ |
| Sign | {:+} |
✅ |
| Alternate | {:#} |
✅ |
| Zero-pad | {:05} |
✅ |
$-parameter width/precision |
{:width$}, {:.prec$} |
✅ |
| Star precision | {:.*} |
✅ |
| Escaped braces | {{ }} |
✅ |
| LowerHex | {:x} |
❌ |
| UpperHex | {:X} |
❌ |
| Octal | {:o} |
❌ |
| Binary | {:b} |
❌ |
| LowerExp | {:e} |
❌ |
| UpperExp | {:E} |
❌ |
| Pointer | {:p} |
❌ |
Note
Only types implementing Display + Debug are supported. Other formatting traits (LowerHex, Binary, Octal, etc.) are not supported and will return Error::UnsupportedTrait.
Note
Local variable interpolation is not supported since template strings are parsed at runtime.
let people = "Rustaceans";
// This will NOT interpolate `people` - use named args instead:
formatx!("Hello {people}!", people = people).unwrap();Dual Licensed