Module fmt/format

fmt/format
Stability: unstable — may still change; see below.

The Format protocol — value.format(spec) (STD_API_AUDIT D3.10).

The spec grammar lives in ./spec.yo; this module is the dispatch layer. Numeric types get radix and sign-aware zero padding; everything else that implements ToString gets width, fill, alignment and truncation from the trait's default format — Rust's model, where fill/align/width are post-processing over whatever the value rendered as.

Example

{ Format } :: import("std/fmt/format");

i32(255).format("#06x");   // "0x00ff"
f64(3.14159).format(".2"); // "3.14"
`ada`.format("<8");        // "ada     "

A type implements Format at most once (plans/reference/TRAIT_COHERENCE.md): the numeric impls below are the only ones with a body of their own, and every other std type that implements ToString implements Format with the trait's DEFAULT format — width, fill, alignment and truncation over to_string(). A type of your own opts in the same way, in one line:

impl(Point, Format());   // needs `impl(Point, ToString(...))`

There is no blanket impl(T <: ToString): it would overlap every numeric impl, and with no specialization one of the two would be dead code. f32 delegates to f64; every integer funnels into one _format_int after splitting itself into sign and magnitude in its own width.

Stability

unstable — it is a thin dispatch layer over ./spec.yo, and it inherits that module's two open questions (no dynamic width or precision, and a parse that never reports a bad spec). It has one of its own: fixed-point float rendering goes through StringBuilder.write_f64, which truncates at 63 bytes, so f64(1.0e300).format(".2") returns 63 digits of a 302-digit number (issues/stddoc-str-string-builder-write-f64-truncates.md). Fixing that changes output. The Format trait itself — one method, spec as a plain str, an unrecognised spec degrading to to_string() — is settled.

Traits / Modules

Format trait
Format

Format a value according to a spec string. Every Format type is also ToString: an unrecognised spec degrades to its to_string().

Methods

format : fn(inout(self) : Self : (ToString), spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing. The default applies width, fill, alignment and truncation to to_string().

Parameters

NameTypeNotes
selfSelf : (ToString)
specstr

Returns: String