Skip to content
CryoCryo home
Stdlibfmt

interpolation

import std::fmt::interpolation; — called by the compiler wherever an f-string appears · source

f-strings

An f-string builds an owned String. Each {expr} hole is rendered through Display, each {expr:?} hole through Debug, and each {expr:#?} through Debug in its pretty form:

const name: Str = "ada";
const count: i32 = 3;
const state: Option<i32> = Option::Some(1);
const line: String = f"user {name} has {count} items";
const dump: String = f"state = {state:?}";

The parser lowers the literal into a chain of calls to the builders in this module, threading one String left to right: a fresh buffer, then a literal piece, a Display hole, a Debug hole, or a hole with a format spec appended in turn. Each builder takes the partial string by value and returns it, so the whole expression evaluates to a single owned String with no intermediate temporaries to drop.

The builders are internal to the standard library: they are the language items format_new, format_append_literal, format_append_display, format_append_debug and format_append_spec (§16.1), and the lowering names them itself, so f"..." works with no import of your own and you never call them by hand.

Types

Arguments

type struct Arguments {
    ![implicit] static from_text(text: string) -> Arguments;
    ![implicit]
    static from_view(text: Str) -> Arguments;
}

An f-string written directly as an argument whose parameter has the type Arguments is not built into a String. It becomes the f-string's pieces — its literal text, and a borrow of each hole's value — and the callee writes them through a Formatter, each hole formatted straight into the sink:

import std::fmt::display::{ Display, Formatter };
import std::fmt::error::{ FormatError };
import std::fmt::write::{ FormatWrite };

type struct Elapsed { public secs: u64; public millis: u64; }

implement trait Display for struct Elapsed {
    fmt(&this, f: mut &Formatter) -> Result<(), FormatError> {
        return f.write(f"{this.secs}.{this.millis:03}s");   // Formatter.write, inside a Display
    }
}

function label(name: Str, code: u32) -> Result<String, FormatError> {
    mut out: String = String::new();
    out.write(f"{name}: {code:04x}")?;   // FormatWrite.write, every sink has it
    return Result::Ok(out);
}

Only that position changes an f-string. Bound to a variable, returned, stored in a field, or passed for a parameter of any other type — a generic T included — it is a String, so a borrow of a hole never outlives the call it is passed to. An Arguments kept past that call names values that may be gone. FormatWrite.write and Formatter.write are how a program writes one; std::fmt re-exports it as fmt::Arguments.