Guides · 03

Structs, enums, and tuples

Vyi has three ways to group values into one:

  • A struct has named fields.
  • An enum is one of several named variants, and a variant can carry data.
  • A tuple has elements in order, with no names.

All three are plain values. Assigning one, passing it to a function, or returning it copies it. Nothing is shared behind your back and nothing is allocated. The guide ends with a fourth kind of value, the structural union A | B, which holds a value of one of several types.

Structs

A struct declares named fields, each with a type. You build one with a literal that gives each field a value, and you read a field with .:

Vyi
import { println } from "@fmt"

struct User {
    name: [*con]u8,
    age: i32,
}

fn main() !u8 {
    con u = User{ name: "ada", age: 36 }
    println(u.name)   // prints ada
    println(u.age)    // prints 36
    return Ok(0)
}

Each struct declaration is its own type, even when another struct has the same fields. Methods belong to that name (guide 04).

Assigning a struct copies it. After the copy, changing one doesn't change the other:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con a = Point{ x: 1, y: 2 }
    mut b = a          // b is a copy of a
    b.x = 100
    println(a.x)       // prints 1
    println(b.x)       // prints 100
    return Ok(0)
}

Every field needs a value or a default

A struct literal must give every field a value. A field you leave out is an error. Vyi never fills it in with zero:

Vyi · does not compile
struct User { name: [*con]u8, age: i32 }

fn main() !u8 {
    con u = User{ name: "ada" }  // error: missing field "age"
    return Ok(0)
}

When a field has a sensible starting value, write it once, in the declaration, as a default: field: T = value. A literal can then leave that field out:

Vyi
import { println } from "@fmt"

struct Server {
    host: [*con]u8,
    port: i32 = 80,
    verbose: bool = false,
}

fn main() !u8 {
    con s = Server{ host: "localhost" }
    con t = Server{ host: "0.0.0.0", port: 8080 }
    println(s.port)   // prints 80
    println(t.port)   // prints 8080
    return Ok(0)
}

A default is an ordinary expression of the field's type. It can be a literal, a struct literal such as Inner{ x: 0, y: 0 }, or a function call. The default runs each time a literal leaves its field out, and fields are set in the order the struct declares them, whether the value comes from the literal or from a default.

A generic struct can use its type parameter in a default. Each version of the struct gets a default of its own type:

Vyi
import { println } from "@fmt"

fn Counter(known T: type) type {
    return struct { count: T, step: T = T(1) }
}

fn main() !u8 {
    con a = Counter(i32){ count: 10 }
    con b = Counter(i64){ count: i64(5) }
    println(a.count + a.step)   // prints 11
    println(b.count + b.step)   // prints 6
    return Ok(0)
}

Guide 11 explains generic types.

So when you read a struct literal, every field was set on purpose: in the literal, or by the declaration's default. Guide 02 gives the same rule for bindings. The one way to get zeros is to ask for them: an array literal with empty brackets, such as [4]u8[], fills the array with zeros (guide 09).

pub fields

A field is private to the file that declares the struct. Mark a field pub to let other files read and write it:

Vyi
// file: user.vyi
export struct User {
    pub name: [*con]u8,
    loginCount: i32 = 0,
}

export fn newUser(name: [*con]u8) User {
    return User{ name: name }
}

// file: main.vyi
import { println } from "@fmt"
import { newUser } from "./user"

fn main() !u8 {
    con u = newUser("ada")
    println(u.name)   // prints ada
    return Ok(0)
}

main.vyi can read u.name because name is pub. Reading u.loginCount there, or setting it in a User{ ... } literal, is an error: field "loginCount" is private to its defining file.

Private fields work well with defaults. Another file can still write a User literal, as long as every private field has a default.

The inferred literal _{ ... }

When the code around a literal already says which struct it must be, you don't have to repeat the name. _ is Vyi's general placeholder for "work this out", and _{ ... } is a struct literal whose type comes from what's expected there: a declared type, a parameter, a return type, or a field:

Vyi
import { println } from "@fmt"

struct Size { width: i32, height: i32 }

fn area(s: Size) i32 { return s.width * s.height }

fn main() !u8 {
    con s: Size = _{ width: 2, height: 3 }
    println(s.width)                           // prints 2
    println(area(_{ width: 4, height: 5 }))    // prints 20
    return Ok(0)
}

Structs that hold pointers

A field can hold a pointer. Guide 09 introduces pointers: &x takes the address of x, and *mut T is the type of a pointer you can write through. A pointer is good only while what it points at exists, so a struct that holds one can't outlive that either. A function can't return a struct that points at one of its own bindings:

Vyi · does not compile
struct Cursor { pos: *mut i32 }

fn start() Cursor {
    mut n = 0
    return Cursor{ pos: &n }   // error: frame-bound pointer
}

Each pointer field has a lifetime of its own, called its slot. Guide 09 covers slots, including how to name one.

Copying into a struct with fewer fields

A struct can be used where a struct with some of its fields is expected. Vyi copies the fields the two have in common and leaves the rest behind. This happens without a written conversion wherever a value goes somewhere with a declared type: a function argument, a return value, a binding with a declared type, or a field in a struct literal.

It's useful when a function needs only part of a larger value. Here printReceipt needs an order's id and total, and the delivery note stays behind:

Vyi
import { println } from "@fmt"

struct Order {
    id: i32,
    total: i32,
    note: [*con]u8,
}

struct Receipt { id: i32, total: i32 }

fn printReceipt(r: Receipt) {
    println($"order ${r.id}: ${r.total}")
}

fn main() !u8 {
    con order = Order{
        id: 7, total: 4200, note: "leave at door",
    }
    printReceipt(order)          // prints order 7: 4200
    con r: Receipt = order
    println(r.total)             // prints 4200
    return Ok(0)
}

The fields match by name, so their order in the declarations doesn't matter. Each field must have the same type on both sides. The result is a copy: changing r never changes order. To make the conversion stand out, write it like a function call named after the target type: Receipt(order).

The copy goes only from more fields to fewer, or between structs with exactly the same fields. A struct with fewer fields can't fill one with more, because Vyi would have to invent the missing values. A default on the missing field doesn't help: defaults apply in a literal, not in a conversion.

Vyi · does not compile
struct Point { x: i32, y: i32 }
struct Vec3  { x: i32, y: i32, z: i32 }

fn main() !u8 {
    con p = Point{ x: 1, y: 2 }
    con v: Vec3 = p   // error: this value has type Point, but the binding is declared Vec3
    return Ok(0)
}

The rule looks only at field names and types. It doesn't know what a struct means. Two structs with the same fields convert into each other in both directions, so a Celsius { degrees: i32 } would copy into a Fahrenheit { degrees: i32 } without complaint, and 100 degrees Celsius would read as 100 degrees Fahrenheit. When two types must never mix, give their fields different names:

Vyi · does not compile
struct Celsius    { celsius: i32 }
struct Fahrenheit { fahrenheit: i32 }

fn main() !u8 {
    con c = Celsius{ celsius: 100 }
    con f: Fahrenheit = c   // error: this value has type Celsius, but the binding is declared Fahrenheit
    return Ok(0)
}

This copy is the only conversion Vyi makes without being asked that leaves data behind. Unions also convert without being asked, but they keep the whole value (structural unions). Numbers never do (guide 02).

Enums

An enum is a fixed set of variants, each with a name unique in the enum. A variant can be bare, or carry a payload of one or more values of any type:

Vyi
enum Shape {
    Dot,                // no payload
    Square(i32),        // side
    Rect(i32, i32),     // width, height
}

You build a variant by calling it, as in Shape.Square(5). The form Enum.Variant always works. When the code around it expects that enum, such as a declared type, a parameter, a return type, or an arm of a match or switch, you can write the variant bare, without the enum's name:

Vyi
import { println } from "@fmt"

enum Shape { Dot, Square(i32), Rect(i32, i32) }

fn area(s: Shape) i32 {
    return match s {
        Dot:        0,
        Square(n):  n * n,
        Rect(w, h): w * h,
    }
}

fn main() !u8 {
    con a = Shape.Square(5)     // with the enum's name
    con b: Shape = Rect(2, 3)   // bare: declared as Shape
    println(area(a))            // prints 25
    println(area(b))            // prints 6
    println(area(Dot))          // prints 0
    return Ok(0)
}

area(Dot) works because the parameter s is a Shape. Bare variants work the same way for every enum. None, Some, Ok, and Err, which guide 07 covers, are ordinary variants of ordinary enums, found exactly the way Dot is here.

A bare variant needs an expected enum type. With none, the compiler can't tell which enum you mean:

Vyi · does not compile
enum Shape { Dot, Square(i32) }

fn main() !u8 {
    con s = Dot       // error: cannot infer enum variant type
    return Ok(0)
}

Write Shape.Dot, or declare the type: con s: Shape = Dot.

Comparing enums

== and != work on an enum when every payload type supports ==. Two values are equal when they're the same variant with equal payloads, so Shape.Square(2) == Shape.Square(2) is true. A struct doesn't support == until you define an @eq method for it (guide 13), so an enum with a struct payload doesn't support it either:

Vyi · does not compile
struct Point { x: i32, y: i32 }

enum Place { Unknown, At(Point) }

fn main() !u8 {
    con home = Place.At(Point{ x: 1, y: 2 })
    con work = Place.At(Point{ x: 1, y: 2 })
    con same = home == work   // error: operator `==` is not
    return Ok(0)
}

Give Point an @eq method and Place compares too, through it. Place can also have an @eq of its own, with the meaning you give it.

Taking enums apart with match

match picks an arm by the variant its subject holds. It must handle every variant, and each arm can bind the payload to new names, as Square(n) and Rect(w, h) do above. Leaving a variant out is a compile error. So when you add a variant to an enum, the compiler lists every match that has to decide what to do with it:

Vyi · does not compile
enum Shape { Dot, Square(i32), Rect(i32, i32) }

fn area(s: Shape) i32 {
    return match s {   // error: non-exhaustive match; missing Rect
        Dot:       0,
        Square(n): n * n,
    }
}

fn main() !u8 {
    return Ok(0)
}

Variants separated by commas share one arm. default: catches every variant the other arms don't name. It counts as handling them, so the compiler stops listing new variants for that match: use it when you mean it. match also gives a value: the arm that runs supplies it:

Vyi
import { println } from "@fmt"

enum Day { Mon, Tue, Wed, Thu, Fri, Sat, Sun }

fn main() !u8 {
    con today = Day.Sat
    con kind = match today {
        Sat, Sun: "weekend",
        default:  "weekday",
    }
    println(kind)   // prints weekend
    return Ok(0)
}

switch is the sibling of match. It chooses by value instead: each arm is a value compared with the subject using ==. An enum whose variants carry no payloads works with either. To bind a payload you need a pattern, so an enum with payloads is taken apart with match. Guide 05 covers both, and guide 06 covers guards, nested patterns, and the single-pattern form if Some(v) = x.

Tuples

A tuple groups values by position, with no declaration and no field names. You write one in parentheses and read its elements with .0, .1, and so on:

Vyi
import { println } from "@fmt"

fn minMax(a: i32, b: i32) (i32, i32) {
    if a < b { return (a, b) }
    return (b, a)
}

fn main() !u8 {
    con r = minMax(9, 4)
    println(r.0)   // prints 4
    println(r.1)   // prints 9
    return Ok(0)
}

A tuple type lists its element types in parentheses, as in (i32, i64). Tuples are values like any other: you can nest them, keep them in struct fields, and pass or return them, which copies them:

Vyi
import { println } from "@fmt"

struct Game {
    home: [*con]u8,
    score: (i32, i32),   // home goals, away goals
}

fn main() !u8 {
    con game = Game{ home: "lions", score: (3, 1) }
    println(game.score.0)   // prints 3

    con line = ((0, 0), (5, 8))   // a start and an end
    println(line.1.0)       // prints 5
    return Ok(0)
}

line.1 is the second element, the tuple (5, 8), and line.1.0 is its first element.

The empty tuple () is the type of a function that returns nothing, and its only value is also written () (guide 02). Because it carries no data, ()!T is a result that is either a T or a failure with nothing to say about it:

Vyi
import { println } from "@fmt"

fn half(n: i32) ()!i32 {
    if n % 2 != 0 { return Err(()) }
    return Ok(n / 2)
}

fn main() !u8 {
    println(half(10) catch 0)   // prints 5
    println(half(7) catch 0)    // prints 0
    return Ok(0)
}

half fails for an odd number. catch 0 gives a value to use when the call fails. Guide 07 covers errors.

Use a tuple when a few values travel together briefly. When the elements deserve names, declare a struct.

Structural unions

A | B is a structural union: a value that is one of the listed types. There is no declaration and there are no variant names. The member types are the cases. A value of any member type is already a value of the union, so you produce a union by returning or assigning one of its members:

Vyi
import { println } from "@fmt"

fn userKey(id: i32) i32 | [*con]u8 {
    if id == 0 { return "guest" }   // a name
    return id                       // a number
}

fn main() !u8 {
    con key = userKey(7)
    match typeof key {
        i32:      println($"user ${key}"),   // prints user 7
        [*con]u8: println(key),
    }
    return Ok(0)
}

A signed-in user's key is their number, and everyone else's is the name "guest". To use the value, branch on which type it holds with match typeof. Inside each arm the value has that arm's type, so key is an i32 in the first arm and a string in the second.

A plain match on a union is an error. A union's cases are types, so you select them through the value's type:

Vyi · does not compile
fn kind(key: i32 | [*con]u8) [*con]u8 {
    return match key {   // error: a union value's members
        i32:      "number",
        [*con]u8: "name",
    }
}

fn main() !u8 {
    return Ok(0)
}

== and != work between a union and a value of one of its member types: userKey(7) == 7 is true, because the union holds an i32 and it equals 7. Two values of the same union are equal when they hold the same member type and those values are equal.

A union also converts on its own into a wider union, one that has all of its member types. This works for bindings, arguments, and return values, and the value inside stays as it was:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con key: i32 | [*con]u8 = "ada"
    con wide: i32 | [*con]u8 | bool = key
    match typeof wide {
        i32:      println("a number"),
        [*con]u8: println(wide),   // prints ada
        bool:     println("a flag"),
    }
    return Ok(0)
}

Errors use unions too. A function that returns !T can fail with any of the error types its body produces, and its error type is the union of them. So handling an error works like handling any other union (guide 07).

The types reference has the complete rules for every type in this guide.