Skip to main content

Crate formatx

Crate formatx 

Source
Expand description

formatx lets you format strings at runtime using the familiar std::fmt syntax [{}, {:?}, {name}, etc.], with runtime template strings instead of compile-time literals. It has zero dependencies and is no_std compatible (requires alloc).

§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!.

§Template Reuse

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");

Macros§

formatx
Format a runtime string in strict mode.
formatxl
Format a runtime string in lenient mode.

Structs§

Renderer
A builder for rendering a Template with arguments.
Template
A parsed format string that can be rendered many times with different arguments.

Enums§

Error
Errors that can occur during parsing or formatting.
FormatArg
A format argument - either a trait object reference or a &str slice.
FormatType
The format trait to use.

Traits§

FormatValue
Marker trait for values that can be formatted at runtime.