macro_rules! fmt {
    (move $($tt:tt)*) => { ... };
    ($($tt:tt)*) => { ... };
}
Expand description

Extended formatting syntax.

Returns a displayable object which can be formatted with {}.

Examples

Basic usage

let name = "World";

fmtools::fmt!("Hello "{name}"!")

The resulting string is Hello World!.

The value arguments can be arbitrary expressions. They are inlined in the formatting braces and are outside the string literals.

Formatting specifiers

let value = 42;

fmtools::fmt!("hex("{value}") = "{value:#x})

The resulting string is hex(42) = 0x2a.

The rules for the specifiers are exactly the same as Rust’s standard formatting syntax.

Let bindings

let base = 52;

fmtools::fmt! {
	let value = base - 10;
	"value = "{value}
}

The resulting string is value = 42.

Control flow

let power = 0.5;

fmtools::fmt! {
	"At "
	if power >= 1.0 { "full" }
	else { {power * 100.0:.0}"%" }
	" power"
}

The resulting string is At 50% power.

let value = Some(42);

fmtools::fmt! {
	"The answer is "
	match value {
		Some(answer) => "Some("{answer}")",
		None => "None",
	}
}

The resulting string is The answer is Some(42).

let values = [1, 2, 3, 4, 5];

fmtools::fmt! {
	for &val in &values {
		let result = val * 5;
		"* "{val}" x 5 = "{result}"\n"
	}
}

The resulting string is:

* 1 x 5 = 5
* 2 x 5 = 10
* 3 x 5 = 15
* 4 x 5 = 20
* 5 x 5 = 25

Control flow really shows the added value of the extended formatting syntax.

Capture by value

fn inner() -> impl std::fmt::Display {
	let a = 42;
	fmtools::fmt!(move "a = "{a})
}
fmtools::fmt!(move "{"{inner()}"}")

The resulting string is {a = 42}.

The displayable object can own the captured variables with move and can be returned from functions.

Escape hatch

fmtools::fmt! {
	"Now entering ["
	|f| f.write_str("escape hatch")?;
	"]"
}

The resulting string is Now entering [escape hatch].

Closure syntax provides an escape hatch to inject code if needed. The argument’s type is &mut Formatter.