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.
Getting Started
Add this to your Cargo.toml file.
[]
= "0.3"
Or add from command line.
See docs and examples to know how to use it.
Examples
Using formatx!
Works just like format!, but accepts runtime template strings.
use formatx;
let template = "{} scored {score:.1}% in {}";
let result = formatx!.unwrap;
assert_eq!;
[!NOTE] Extra arguments that aren't referenced by any placeholder are silently ignored in both
formatx!andformatxl!.
Template Reuse
Parse once, render many times with Template.
use Template;
let template = new.unwrap;
let r1 = template.render
.named
.named
.finish
.unwrap;
let r2 = template.render
.named
.named
.finish
.unwrap;
assert_eq!;
assert_eq!;
Supported Syntax
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+Debugare supported. Other formatting traits (LowerHex,Binary,Octal, etc.) are not supported and will returnError::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!.unwrap;
Status
License
Dual Licensed