Guides · 10
Collections and strings
This guide covers text and the growable containers: string literals, the
String type, printing and string templates, Vec(T) for lists, and
HashMap(K, V) for lookups. It ends with how for loops over a collection,
including one you write yourself.
String, Vec, and HashMap live in the @core package. They are ordinary
library types, so you import them like anything else, as in
import { Vec } from "@core". Vyi has no list or map literal syntax. You build
a container empty and add to it.
Containers take an allocator
A container needs memory that can grow while the program runs, and in Vyi that memory always comes from an allocator you pass in. Nothing allocates unless you hand it an allocator, so the memory a container uses is visible where you create it. Guide 09, Pointers and memory, covers allocators in full.
Every example in this guide sets up memory the same way:
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut scores = Vec(i32).new(&arena)
scores.push(80)
scores.push(95)
println(scores.length()) // prints 2
return Ok(0)
}ArenaAllocator hands out memory from large chunks it takes from another
allocator, here systemAllocator, the platform heap. Nothing it hands out is
freed one piece at a time: arena.deinit() returns all of it at once, and
defer runs that when main exits.
A container's constructor takes an Allocator, which is an interface (guide
12). systemAllocator is already an Allocator value, so
you pass it as it is. An arena is a struct, and &arena turns a pointer to it
into an Allocator, the same way &d turned a pointer to a Dog into a
Speaker in guide 01. arena.allocator()
returns the same value, for code that prefers a method call.
When a container can't get memory, it panics with out of memory. push and
the other growing operations return no error for you to handle. Guide
07 explains where Vyi draws the
line between an error and a panic.
Strings
String literals are bytes
A "" literal is UTF-8 text stored in the program itself. Its type is
[*con]u8: a read-only view of bytes with a length, the array pointer from
guide 09. Indexing
it gives a byte, and .len is its length in bytes:
import { println } from "@fmt"
fn main() !u8 {
con greeting = "hello"
println(greeting) // prints hello
println(greeting[0]) // prints 104
println(greeting.len) // prints 5
con accent: char = 'é'
println(accent) // prints é
println(u32(accent)) // prints 233
return Ok(0)
}greeting[0] is the byte 104, the code for h. A '' literal is a char:
one whole Unicode code point, 32 bits wide. For ASCII text a byte and a code
point are the same number. Outside ASCII they differ: 'é' is the code point
233, which UTF-8 stores as two bytes.
A literal can't change and you can't add to it. To build, join, or keep text,
copy it into a String.
The String type
A String holds UTF-8 bytes in allocator memory, together with the allocator
they came from. It counts and indexes its text in code points.
String.fromUtf8(alloc, bytes) copies bytes, usually a literal, into a new
String:
import { String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con drink = String.fromUtf8(&arena, "café")
println(drink.asBytes()) // prints café
println(drink.length()) // prints 4
println(drink.byteLen()) // prints 5
return Ok(0)
}println prints a [*con]u8. To print a String, or put one in a string
template (below), pass s.asBytes(), which returns a view of the string's
bytes without copying them. (Importing String.intoString from @fmt lets
println take the String itself.) (A String also has a public bytes field holding the same
view; asBytes() is the method to use, and Buffer below has one too.)
length() counts code points and byteLen() counts bytes. They are equal for
ASCII text and differ as soon as the text has anything else: café is 4 code
points in 5 bytes. Both are stored, so asking is instant.
A String never changes once built. Indexing, slicing, ==, and + work on
it:
import { String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con first = String.fromUtf8(&arena, "Ada")
con last = String.fromUtf8(&arena, " Lovelace")
con name = first + last
println(name.asBytes()) // prints Ada Lovelace
println(name[0]) // prints A
println(name[0..3].asBytes()) // prints Ada
println(name[0..3] == first) // prints true
return Ok(0)
}In detail:
s[i]is the code point at positioni, as achar. Positions count from 0, so the last one iss[s.length() - 1]. A position outside0 <= i < s.length(), including a negative one, panics. Finding positionimeans decoding the text from the start, sos[i]takes time proportional toi.s[lo..hi]is a newStringfor the code points fromloup to, not including,hi. It shares the original's bytes instead of copying them. Leave off the end to run to the end:s[2..].s == tcompares bytes. Two spellings of the same character, such aséas one code point or aseplus a combining accent, compare unequal.s + tcopies both into a newString, usings's allocator. This is why aStringcarries its allocator:a + b + cneeds no allocator passed in.
For work on bytes there are s.byteAt(i) and s.indexOfByte(b), which
returns -1 when the byte isn't there. s.isEmpty(), s.startsWith(prefix),
and s.endsWith(suffix) answer the obvious questions; prefix and suffix
are Strings too.
Building a string
String.new(alloc) makes an empty string to build on, += appends, and
repeat(n) repeats a string n times:
import { String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con laugh = String.fromUtf8(&arena, "ha")
mut line = String.new(&arena)
line += laugh
line += laugh
println(line.asBytes()) // prints haha
println(laugh.repeat(3).asBytes()) // prints hahaha
return Ok(0)
}line += laugh is line = line + laugh: it makes a new string and copies both
parts into it. Building a long string one piece at a time therefore copies the
early pieces again and again. For short strings in an arena that cost is small.
For long output, render into a Buffer instead (below).
Printing
print and println from @fmt write one value to standard output; println
adds a newline. Neither takes a format string or an allocator:
import { print, println } from "@fmt"
fn main() !u8 {
print("answer = ")
println(42) // prints answer = 42
println(true) // prints true
return Ok(0)
}They print integers of every width, bool, char, and byte strings
([*con]u8). Floating-point numbers can't be printed yet: println on an
f64 is a compile error.
Printing your own types
println prints any value whose type has an intoString method. That method
writes the value onto a Writer, the @io interface for anything that accepts
bytes, and returns how many bytes it wrote:
import { Writer } from "@io"
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn (p: Point) intoString(w: Writer) error!i32 {
mut written = try w.write("(")
written += try p.x.intoString(w)
written += try w.write(", ")
written += try p.y.intoString(w)
written += try w.write(")")
return Ok(written)
}
fn main() !u8 {
println(Point{ x: 3, y: 4 }) // prints (3, 4)
return Ok(0)
}Point prints its fields by calling their own intoString. Writing can fail
(standard output might be closed), so each write is a try, and the method
returns error!i32. The method writes straight onto the Writer instead of
returning a string, so printing allocates nothing, and the same method can
write to standard output, a file, or a Buffer in memory. In @fmt the method
belongs to the IntoString interface.
String templates
A string written with a $ in front, $"...", is a template. Each ${expr}
inside it is a hole: the value of expr is printed in its place.
import { println } from "@fmt"
fn main() !u8 {
con user = "ada"
con unread = 3
println($"${user} has ${unread} messages") // prints ada has 3 messages
return Ok(0)
}A hole takes any expression, such as ${unread + 1} or ${user.len}. Its
value can be of any type println accepts, including your own types with an
intoString method.
To write a $ followed by { as text, escape the dollar: \${. Here \$
is a plain dollar sign and the ${price} after it is a hole:
import { println } from "@fmt"
fn main() !u8 {
con price = 15
println($"total: \$${price}") // prints total: $15
return Ok(0)
}A $ before anything other than { is plain text. Other escapes work as in
ordinary strings, and a template stays on one line.
A plain string treats ${ as an error, because it almost always means a
missing $:
import { println } from "@fmt"
fn main() !u8 {
con unread = 3
println("unread: ${unread}") // error: interpolation is only available
return Ok(0)
}A template is a value
A template is not a string. It's a value of type Template (from @fmt) that
renders its text when it's printed. The holes are evaluated once, where the
template is written, and the template keeps those values:
import { println } from "@fmt"
fn main() !u8 {
mut count = 7
con report = $"count = ${count}"
count += 1
println(report) // prints count = 7
println(report) // prints count = 7
return Ok(0)
}report captured count when it was 7, so changing count afterwards
doesn't change what report prints.
A template lives in the block where it's written, like a closure (guide
04). You can pass it to a function, which takes
it as a Template parameter, but a function can't return one. To keep the text
longer, turn it into a String.
Rendering a template elsewhere
t.string(alloc) renders a template into a new String. Rendering can fail,
so the call is a try:
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con id = 42
con label = try $"order-${id}".string(&arena)
println(label.asBytes()) // prints order-42
return Ok(0)
}t.intoString(w) renders a template onto any Writer, the same method
println calls.
Writing into memory with Buffer
A Buffer from @mem collects bytes in allocator memory. It is a Writer, so
anything that renders onto a Writer can render into it:
import { Buffer, ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con user = "ada"
mut log = Buffer.fromAlloc(&arena)
try $"user ${user}".intoString(&log)
try log.write(" signed in")
println(log.asBytes()) // prints user ada signed in
return Ok(0)
}The buffer grows through its allocator as you write. When it runs out of room it
takes a larger block and copies the bytes over; this is why a write can fail
with OutOfMemory, which try passes on.
log.asBytes() is a view of what's been written so far, valid until the buffer
grows again. Two methods hand the bytes over for keeps:
b.bytes(alloc)copies them into new memory fromalloc. The buffer stays usable.b.takeBytes()gives you the buffer's own memory without copying. The buffer is finished after that: writing to it again panics.
Buffered output
Each println writes to standard output directly once it has rendered its
value. When you write many small pieces to a stream yourself, a
BufferedWriter from @io collects them and sends them on in one go. You give
it the memory to collect in, and it sends the bytes when you call flush:
import { BufferedWriter, stdout } from "@io"
import { systemAllocator } from "@mem"
fn main() !u8 {
con storage = try systemAllocator.alloc(64, 1)
defer systemAllocator.free(storage)
mut out = BufferedWriter.new(&stdout, storage)
try out.write("one ")
try out.write("two ")
try out.write("three\n")
try out.flush() // prints one two three
return Ok(0)
}Nothing flushes a BufferedWriter for you. Bytes still in it when it goes out
of scope are lost, so call flush before you're done. When a write doesn't fit
in the space left, the writer flushes what it holds first, and a write larger
than the whole storage goes straight through.
Reading has a matching type, BufferedReader. Its readLine() returns the next
line as a ?[*con]u8, None at the end of the input, inside an error union
because reading can fail. readAll(alloc) reads the whole stream into memory
from alloc.
Vec(T)
A Vec(T) is a list of T values that grows as you add to them. It keeps its
elements side by side in one block of allocator memory:
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut scores = Vec(i32).new(&arena)
scores.push(80)
scores.push(95)
println(scores.length()) // prints 2
println(scores[1]) // prints 95
scores[1] = 100
println(scores[1]) // prints 100
return Ok(0)
}pushadds to the end. TheVecstarts with room for 16 elements; pass a second argument tonewto choose another number. When it's full,pushtakes a block twice the size (at least 8) and copies the elements over.- Indexing is checked.
v[i]reads andv[i] = xwrites the element at positioni, counting from 0. A position outside0 <= i < v.length(), including a negative one, panics. - Elements are stored directly. A
Vec(Point)holds thePointstructs themselves, one after another, not pointers to them. length()is the number of elements. The fieldsitems(the whole block),cap(how many elements fit before it grows), andallocare public; you rarely need them.
Slices of a Vec
v[lo..hi] gives a [*mut]T view of elements lo up to, not including, hi,
without copying. The view points into the Vec's current block. When a later
push grows the Vec, its elements move to a new block and the view still
points at the old one:
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut scores = Vec(i32).new(&arena, 2)
scores.push(10)
scores.push(20)
con firstTwo = scores[0..2]
scores.push(30) // full: moves to a bigger block
scores[0] = 99
println(scores[0]) // prints 99
println(firstTwo[0]) // prints 10
return Ok(0)
}The compiler doesn't catch this, and neither does the running program: the old
view reads stale values, and writes through it don't reach the Vec. Take a
slice after you've finished adding, and don't keep it across a push.
Elements of any type
The element type can be anything, structs included:
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { print, println } from "@fmt"
struct Item { name: [*con]u8, price: i32 }
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut cart = Vec(Item).new(&arena)
cart.push(Item{ name: "tea", price: 4 })
cart.push(Item{ name: "bread", price: 3 })
for item in cart {
print($"${item.name} ")
}
println("") // prints tea bread
return Ok(0)
}HashMap(K, V)
A HashMap(K, V) maps keys of type K to values of type V. put adds or
replaces an entry, get looks one up, contains tests for one, and remove
deletes one:
import { HashMap, String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con ada = String.fromUtf8(&arena, "ada")
con alan = String.fromUtf8(&arena, "alan")
mut ages = HashMap(String, i32).new(&arena)
ages.put(ada, 36)
ages.put(alan, 41)
ages.put(ada, 37) // replaces 36
match ages.get(ada) {
Some(age): println(age), // prints 37
None: println("no age"),
}
println(ages.contains(alan)) // prints true
ages.remove(alan)
println(ages.length()) // prints 1
return Ok(0)
}A missing key has no value to return, so get returns ?V, an optional
(guide 07). match on it as above, or use
catch to supply a value for the missing case:
import { HashMap } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut stock = HashMap(i32, i32).new(&arena)
stock.put(101, 5)
println(stock.get(101) catch 0) // prints 5
println(stock.get(999) catch 0) // prints 0
return Ok(0)
}remove returns true when it removed an entry. The map grows by itself when
it's seven-eighths full.
What can be a key
The map finds a key's place with the key's @hash() method, and compares keys
with ==. Any type with a @hash() u32 method and == works as a key. @core
gives every integer type, char, and String a @hash. For your own type,
write both methods; == on a struct calls its @eq method (guide
13):
import { HashMap } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
struct Cell { row: i32, col: i32 }
fn (c: Cell) @hash() u32 {
return u32(c.row) * 31 + u32(c.col)
}
fn (c: Cell) @eq(other: Cell) bool {
return c.row == other.row && c.col == other.col
}
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut sheet = HashMap(Cell, i32).new(&arena)
sheet.put(Cell{ row: 1, col: 2 }, 12)
println(sheet.get(Cell{ row: 1, col: 2 }) catch 0) // prints 12
return Ok(0)
}Keys that are equal must hash to the same number, or the map won't find them.
The 31 spreads rows apart so that (1, 2) and (2, 1) hash differently.
Iterating a map
for entry in map visits each entry once. Each entry is an Entry(K, V), a
struct with fields key and value. keys(), values(), and entries()
copy the map's contents into a new Vec, using the map's allocator; later
changes to the map don't affect that Vec.
import { HashMap } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut stock = HashMap(i32, i32).new(&arena)
stock.put(101, 5) // product 101: 5 in stock
stock.put(102, 3)
mut total = 0
for entry in stock {
total += entry.value
}
println(total) // prints 8
con ids = stock.keys()
println(ids.length()) // prints 2
return Ok(0)
}The order of the entries is not specified, and it can change when the map grows. Don't rely on it.
How for loops over a collection
for x in c works for any type that has either an @iter() method, or an
@index(i: i32) method and a length() method. @core's types use these
same methods; nothing about them is special.
The iterator protocol
When the type has @iter(), the loop calls it once to get an iterator. An
iterator is any value with a @next() method that returns ?T. The loop calls
@next() each time round: Some(x) is the next item, and None ends the
loop. String loops over its code points this way, and HashMap over its
entries.
import { print, println } from "@fmt"
struct Countdown { remaining: i32 }
fn (c: Countdown) @iter() Countdown {
return c
}
fn (c: *mut Countdown) @next() ?i32 {
if c.remaining == 0 {
return None
}
con current = c.remaining
c.remaining -= 1
return Some(current)
}
fn main() !u8 {
con launch = Countdown{ remaining: 3 }
for n in launch {
print($"${n} ")
}
println("liftoff") // prints 3 2 1 liftoff
println(launch.remaining) // prints 3
return Ok(0)
}Countdown is its own iterator: @iter returns a copy of it. @next takes a
*mut Countdown receiver because it advances the iterator in place. The loop
works on its copy, so launch itself still counts from 3 afterwards.
A @next() that returns ?*mut T hands the loop a pointer to each element, so
the loop body can change elements in place.
The index protocol
A type without @iter() is looped over by position: the loop reads c[0],
c[1], and so on up to c[c.length() - 1]. Vec works this way, and so do
array pointers such as [*con]u8, which is how a loop over a string literal
visits its bytes. A type of your own works the same way:
import { print, println } from "@fmt"
struct Seats { count: i32 }
fn (s: Seats) @index(i: i32) i32 {
return i + 1 // seats are numbered from 1
}
fn (s: Seats) length() i32 {
return s.count
}
fn main() !u8 {
con row = Seats{ count: 3 }
for seat in row {
print($"${seat} ")
}
println("") // prints 1 2 3
return Ok(0)
}Looping over a string
for ch in s visits a String's code points as chars, decoding each one once,
so the loop takes time proportional to the length of the text:
import { String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { print, println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con city = String.fromUtf8(&arena, "Zürich")
for ch in city {
print($"${ch} ")
}
println("") // prints Z ü r i c h
return Ok(0)
}for b in city.asBytes() visits the bytes instead: seven of them, because
ü takes two.
Avoid looping over positions and indexing, as in for i in 0..s.length() with
s[i] in the body: each s[i] decodes from the start of the text, so the
whole loop takes time proportional to the square of the length.
for doesn't give you the position of the current item. To have one, keep a
counter yourself, or loop over the positions with for i in 0..v.length() and
index.
See also: reference/stdlib/core for every method on these types, and guide 09, Pointers and memory for allocators.