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.

Vyi
import { print, println } from "@fmt"
import { IntoString, Template } from "@fmt"
import { Buffer.intoString } from "@fmt"

Exports

NameKindSummary
printfunctionwrites one value to standard output
printlnfunctionwrites one value and a newline to standard output
IntoStringinterfaceanything that can write itself onto a Writer
Templatestructthe value of a $"..." template
intoStringmethodsIntoString for the integer types, bool, char, [*con]u8, Buffer, and Template
stringmethod on Templatethe rendered text as a String

Nothing in @fmt allocates except Template.string.

FunctionSignatureResult
printfn print(v: _)writes v to standard output
printlnfn println(v: _)writes v and then \n to standard output
  • Each takes exactly one value, of any type that has an intoString method (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 stdout when full and at the end of the call. Each call writes all of its output before it returns, so print, println, and direct writes to stdout from @io can 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).
Vyi
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:

TypePrints
i8, i16, i32, i64base 10, with - when negative
u8, u16, u32, u64base 10
iw, uwbase 10
f32, f64the 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
booltrue or false
charthe code point as UTF-8; code points up to U+FFFF only (above that, the output is not valid UTF-8)
[*con]u8the bytes as they are
Buffer from @memthe bytes written to it
Templatethe rendered template
your own typewhat 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:

Vyi
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:

ValueWrite 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]u8println([*con]u8(view))
(), an enum, a struct, a tuple, an optional or result, a fixed array, another array pointerwrite 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:

Vyi · does not compile
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)
}
Vyi
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

Vyi
import { Writer } from "@io"

interface IntoString {
    fn (s: ~IntoString) intoString(w: Writer) error!i32,
}
MethodContract
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:

Vyi
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

ReceiverSignature
each integer type Tfn (n: T) intoString(w: Writer) error!i32
boolfn (v: bool) intoString(w: Writer) error!i32
charfn (ch: char) intoString(w: Writer) error!i32
[*con]u8fn (s: [*con]u8) intoString(w: Writer) error!i32
Bufferfn (b: Buffer) intoString(w: Writer) error!i32
Templatefn (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:

Vyi
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:

Vyi
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.

MemberSignatureResult
intoStringfn (t: Template) intoString(w: Writer) error!i32writes the text onto w; returns the bytes written
stringfn (t: Template) string(a: Allocator) error!Stringthe text as a new String in memory from a
fieldpub 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 Template parameter and stored in a local binding. A function cannot return one: return t is reported as frame-bound pointer Template escapes via return. To keep the text, call string.
  • string fails with OutOfMemory (an @mem error) when a runs out. The bytes belong to a.
Vyi
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.