Docs · Standard library
@fmt
@fmt holds print and println, the IntoString interface that decides
what they can print, the intoString methods for the primitive types, and
Template, the type of a $"..." string template. Guide
10, Collections and strings
teaches printing and templates.
import { print, println } from "@fmt"
import { IntoString, Template } from "@fmt"
import { Buffer.intoString } from "@fmt"Exports
| Name | Kind | Summary |
|---|---|---|
print | function | writes one value to standard output |
println | function | writes one value and a newline to standard output |
IntoString | interface | anything that can write itself onto a Writer |
Template | struct | the value of a $"..." template |
intoString | methods | IntoString for the integer types, bool, char, [*con]u8, Buffer, and Template |
string | method on Template | the rendered text as a String |
Nothing in @fmt allocates except Template.string.
print and println
| Function | Signature | Result |
|---|---|---|
print | fn print(v: _) | writes v to standard output |
println | fn println(v: _) | writes v and then \n to standard output |
- Each takes exactly one value, of any type that has an
intoStringmethod (the next section). There is no format string; use a template to combine values. v: _takes the argument's own type, so a value is passed as it is:println(42),println(point), with no&.- Output is collected in 64 bytes on the stack and sent to
stdoutwhen full and at the end of the call. Each call writes all of its output before it returns, soprint,println, and direct writes tostdoutfrom@iocan be mixed. - Neither returns anything. A failed write to standard output is ignored. To see the failure, write the value yourself:
try v.intoString(&stdout).
import { print, println } from "@fmt"
fn main() !u8 {
print("score: ")
println(42) // prints score: 42
println(true) // prints true
println('é') // prints é
return Ok(0)
}What can be printed
print, println, and a template hole accept a value whose type has an
intoString method that the call can find:
| Type | Prints |
|---|---|
i8, i16, i32, i64 | base 10, with - when negative |
u8, u16, u32, u64 | base 10 |
iw, uw | base 10 |
f32, f64 | the shortest digits that read back as the same value, always with a point: 4.5, 3.0, 0.30000000000000004; very large and very small values use an exponent, as in 1.0e24 |
bool | true or false |
char | the code point as UTF-8; code points up to U+FFFF only (above that, the output is not valid UTF-8) |
[*con]u8 | the bytes as they are |
Buffer from @mem | the bytes written to it |
Template | the rendered template |
| your own type | what its intoString method writes (below) |
A String prints once its intoString method is in scope. Import String
from @core to use the type, and String.intoString from @fmt to print
it:
import { String } from "@core"
import { println, String.intoString } from "@fmt"
import { ArenaAllocator, systemAllocator } from "@mem"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con drink = String.fromUtf8(&arena, "café")
println(drink) // prints café
println($"one ${drink}") // prints one café
return Ok(0)
}Without that import, print the bytes: println(drink.asBytes()).
These types have no intoString method, so they cannot be printed directly.
Convert the value first:
| Value | Write instead |
|---|---|
a value of a single-value type, such as type Five = 5 or a narrowed "fast" | the value as its base type: println(i32(n)); for text, bind it as [*con]u8 first |
a [*mut]u8 | println([*con]u8(view)) |
(), an enum, a struct, a tuple, an optional or result, a fixed array, another array pointer | write an intoString method, or print the parts |
Passed to print or println, such a value is reported inside @fmt as
`type Point has no method "intoString" (for a struct Point`), with a note
pointing at your call. In a template hole, the same error points at the hole:
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn main() !u8 {
con start = Point{ x: 1, y: 2 }
println($"start: ${start}") // error: type Point has no method "intoString"
return Ok(0)
}import { println } from "@fmt"
type Five = 5
fn main() !u8 {
con n: Five = 5
println(i32(n)) // prints 5
con mode: "fast" | "slow" = "fast"
con text: [*con]u8 = mode
println(text) // prints fast
println(4.5) // prints 4.5
println(iw(-3)) // prints -3
return Ok(0)
}IntoString
import { Writer } from "@io"
interface IntoString {
fn (s: ~IntoString) intoString(w: Writer) error!i32,
}| Method | Contract |
|---|---|
intoString(w) | writes the value's text onto w and returns the number of bytes written, or the Writer's error |
print and println do not take an IntoString parameter: they call
v.intoString(...) on the value's own type. Use IntoString as a parameter
type to accept any printable value:
import { IntoString } from "@fmt"
import { stdout } from "@io"
fn labeled(label: [*con]u8, v: IntoString) error!i32 {
mut written = try stdout.write(label)
written += try v.intoString(&stdout)
written += try stdout.write("\n")
return Ok(written)
}
fn main() !u8 {
con unread = 3
try labeled("unread: ", &unread) // prints unread: 3
return Ok(0)
}The primitives' intoString
| Receiver | Signature |
|---|---|
each integer type T | fn (n: T) intoString(w: Writer) error!i32 |
bool | fn (v: bool) intoString(w: Writer) error!i32 |
char | fn (ch: char) intoString(w: Writer) error!i32 |
[*con]u8 | fn (s: [*con]u8) intoString(w: Writer) error!i32 |
Buffer | fn (b: Buffer) intoString(w: Writer) error!i32 |
Template | fn (t: Template) intoString(w: Writer) error!i32 |
The methods on the integer types, bool, char, [*con]u8, and Template
are callable in any file that imports @fmt, with any import form, including
import "@fmt". Buffer's is imported by name, as Buffer.intoString:
import { Buffer.intoString } from "@fmt"
import { stdout } from "@io"
import { Buffer, ArenaAllocator, systemAllocator } from "@mem"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut log = Buffer.fromAlloc(&arena)
try log.write("saved\n")
try log.intoString(&stdout) // prints saved
return Ok(0)
}print(buffer) and println(buffer) work without that import.
Printing your own types
Give the type a method with the same signature, `intoString(w: Writer)
error!i32. print, println`, and template holes find it in the type's
pocket, so define it beside the type, and export it beside an exported type
(methods travel with types).
Write each part with w.write or the part's own intoString:
import { Writer } from "@io"
import { println } from "@fmt"
struct Money { cents: i32 }
fn (m: Money) intoString(w: Writer) error!i32 {
mut written = try w.write("$")
written += try (m.cents / 100).intoString(w)
written += try w.write(".")
if m.cents % 100 < 10 { written += try w.write("0") }
written += try (m.cents % 100).intoString(w)
return Ok(written)
}
fn main() !u8 {
println(Money{ cents: 1205 }) // prints $12.05
return Ok(0)
}Templates
A template literal, $"text ${expr} text", is a Template value. Each hole
is evaluated once, where the literal is written, and the template keeps the
values. A hole takes any value that println takes. The
lexical reference gives the literal's syntax.
| Member | Signature | Result |
|---|---|---|
intoString | fn (t: Template) intoString(w: Writer) error!i32 | writes the text onto w; returns the bytes written |
string | fn (t: Template) string(a: Allocator) error!String | the text as a new String in memory from a |
| field | pub render: fn(w: Writer) (error!i32) | set by the template literal; render through the methods |
- A template lives in the block where it is written, like a closure. It can be passed to a function as a
Templateparameter and stored in a local binding. A function cannot return one:return tis reported asframe-bound pointer Template escapes via return. To keep the text, callstring. stringfails withOutOfMemory(an@memerror) whenaruns out. The bytes belong toa.
import { println, Template } from "@fmt"
import { stdout } from "@io"
import { ArenaAllocator, systemAllocator } from "@mem"
fn shout(t: Template) error!i32 {
mut written = try t.intoString(&stdout)
written += try stdout.write("!\n")
return Ok(written)
}
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con user = "ada"
try shout($"hello ${user}") // prints hello ada!
con id = 42
con label = try $"order-${id}".string(&arena)
println(label.asBytes()) // prints order-42
return Ok(0)
}See also: guide 10, Collections and strings,
@io for Writer and stdout, @mem for
Buffer, and @core for number formatting.