Macro const_format::formatc

source ·
macro_rules! formatc {
    ($format_string:expr $( $(, $expr:expr )+ )? $(,)? ) => { ... };
}
Available on crate feature fmt only.
Expand description

Formats constants of standard library and/or user-defined types into a &'static str.

User-defined types must implement the FormatMarker trait (as described in the docs for that trait) to be usable with this macro.

Stable equivalent

For an equivalent macro which can be used in stable Rust, but can only format primitive types, you can use the formatcp macro.

Syntax

This macro uses the syntax described in the const_format::fmt module

Limitations

This macro has the limitations described in here.

Example

#![feature(const_mut_refs)]

use const_format::for_examples::Point3;
use const_format::formatc;

// Formatting a non-std struct.
const POINT: &str = formatc!("{:?}", Point3{x: 8, y: 13, z: 21});

// Formatting a number as decimal, hexadecimal, and binary
const NUMBER: &str = formatc!("{0},{0:x},{0:b}", 10u8);

// Formatting the numbers in an array as decimal, hexadecimal, and binary.
// You can use the name of cnstants from scope, as well as named arguments.
const ARR: &[u32] = &[9, 25];
const ARRAY: &str = formatc!("{ARR:?},{ARR:X},{ARR:b}");


assert_eq!(POINT, "Point3 { x: 8, y: 13, z: 21 }");
assert_eq!(NUMBER, "10,a,1010");
assert_eq!(ARRAY, "[9, 25],[9, 19],[1001, 11001]");

Custom formatting.

This example demonstrates how you can access the Formatter in arguments to do custom formatting.

For more details on this you can look in the fmt module.

#![feature(const_mut_refs)]

use const_format::for_examples::Point3;
use const_format::{formatc, try_};

const P: Point3 = Point3{x: 5, y: 13, z: 21};

const STR: &str = formatc!("{0};{0:#X};{0:#b}", |fmt|{
    try_!(fmt.write_u32_debug(P.x));
    try_!(fmt.write_str(" "));
    try_!(fmt.write_u32_debug(P.y));
    try_!(fmt.write_char('.'));
});

assert_eq!(STR, "5 13.;0x5 0xD.;0b101 0b1101.");