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.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const name: Strtype struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
const count: i32const state: Option<i32>type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
Option::Some(T)const line: Stringtype struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
const name: Strconst count: i32const dump: String(parameter) state: ?type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Arguments {}Text formatted where it is written. An f-string written directly as an argument whose parameter has this type 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 (FormatWrite.write), each hole…
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static Arguments::from_text(text: string) -> Arguments(parameter) text: stringprimitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.
type struct Arguments {}Text formatted where it is written. An f-string written directly as an argument whose parameter has this type 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 (FormatWrite.write), each hole…
static Arguments::from_view(text: Str) -> ArgumentsA view as the arguments that write it. ![implicit], so a Str is converted where an Arguments is declared.
(parameter) text: Strimport a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.
type struct Formatter {}Where a Display or Debug implementation writes its text: a sink (standard output, a String, a file) with the format's options. write_str writes text; debug_struct and debug_tuple lay out a value's members.
type enum FormatError {
Io(IoError);
Allocation(AllocationError);
}Why formatting a value failed: the sink refused the bytes, or a sink that grows (a String) could not.
type trait FormatWrite {
write_str(mut &this, source: Str) -> Result<(), FormatError>;
write_char(mut &this, c: char) -> Result<(), FormatError>;
write(mut &this, arguments: Arguments) -> Result<(), FormatError>;
}A text sink a Formatter writes into: standard output, a String, a file. An implementation provides write_str.
type struct Elapsedpublic function name() { ... }
public:Visible to any module that imports this one - the default for top-level items and for struct fields, so it is mostly written to be explicit. public: opens a visibility block that groups the members after it. A module is always public, so public module is refused (E0117).
Elapsed.secs: u64Elapsed.millis: u64implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referenceimplement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype struct ElapsedElapsed::fmt(&this, f: mut &Formatter) -> Result<(), FormatError>&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) f: mut &Formattermut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
(parameter) f: mut &FormatterFormatter::write(mut &this, arguments: Arguments) -> Result<(), FormatError>Write an f-string, f.write(f"{a}..{b}"), each hole formatted straight into the sink, as FormatWrite.write does.
Elapsed.secs: u64Elapsed.millis: u64function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function label(name: Str, code: u32) -> Result<String, FormatError>(parameter) name: Str(parameter) code: u32mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut out: Stringstatic String::new() -> StringEmpty string. No heap storage until the first append, push or reserve.
mut out: StringString::write(mut &this, arguments: Arguments) -> Result<(), FormatError>via trait FormatWrite
Write an f-string, sink.write(f"x = {x}"), formatting each hole straight into this sink: an f-string written here is the Arguments of its pieces, not a String (fmt::Arguments).
(parameter) name: Str(parameter) code: ?value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
Result::Ok(T)type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.