Tern

5. Structs

A struct groups related values under one name. This chapter shows how to define structs, build them, read and change their fields, nest them, and give them "methods" by writing ordinary functions. Tern has no classes, self, or inheritance; structs plus functions cover the same ground with less machinery.

Defining and building a struct

A struct lists its fields and their types. Fields of the same type can share a line:

struct Book:
    title: str
    author: str
    year: int
    rating: float

struct Point:
    x, y: int

fn main():
    b = Book("Dune", "Frank Herbert", 1965, 4.5)
    c = Book(title="Emma", author="Jane Austen", rating=4.0, year=1815)
    print(b.title, "by", b.author)
    print(c.year, c.rating)
    print(Point(3, -1))
    print(b)
Output
Dune by Frank Herbert
1815 4.0
Point{x: 3, y: -1}
Book{title: "Dune", author: "Frank Herbert", year: 1965, rating: 4.5}

You build a struct by calling its name like a function. Give the fields in order, or name them (title="Emma") in any order. Named arguments exist only for this: they make long constructor calls readable, and they don't break when someone reorders the fields.

print shows a whole struct as Name{field: value, ...}, which is handy while debugging.

Every field is required

A struct has no default field values, and every field must be given:

Does not compile
struct Point:
    x, y: int

fn main():
    p = Point(1)
    print(p.z)
Compiler output
5: error: missing field `y` in Point
6: error: Point has no field `z`

When you want defaults, write a function that builds the struct. By convention it is named new_something:

struct Settings:
    volume: int
    muted: bool
    theme: str

fn new_settings() Settings:
    return Settings(volume=50, muted=false, theme="light")

fn main():
    s = new_settings()
    s.theme = "dark"
    print(s)
Output
Settings{volume: 50, muted: false, theme: "dark"}

Changing fields

Fields of a struct in a variable can be assigned directly, including fields of nested structs and arrays inside the struct:

struct Point:
    x, y: int

struct Player:
    name: str
    pos: Point
    inventory: [str]

fn main():
    hero = Player("Robin", Point(0, 0), [])
    hero.pos.x += 3
    hero.pos.y = -2
    hero.inventory.push("rope")
    hero.inventory.push("lamp")
    print(hero.name, "is at", hero.pos.x, hero.pos.y)
    print(hero.inventory)
Output
Robin is at 3 -2
["rope", "lamp"]

Methods are functions

To give a struct behavior, write a function that takes it as the first parameter. Thanks to method-call syntax (chapter 4), you can call it with a dot:

struct Rect:
    w, h: float

fn area(r: Rect) float:
    return r.w * r.h

fn is_square(r: Rect) bool:
    return r.w == r.h

fn scaled(r: Rect, k: float) Rect:
    return Rect(r.w * k, r.h * k)

fn main():
    r = Rect(2.0, 3.0)
    print(r.area(), r.is_square())
    big = r.scaled(10.0)
    print(big, big.area())
    print(area(r))
Output
6.0 false
Rect{w: 20.0, h: 30.0} 600.0
6.0

r.area() and area(r) are the same call. There is no special "inside the struct" scope: a method is just a function, so it can live in any file and anyone can add one.

Notice that scaled returns a new Rect instead of changing r. That is the natural style in Tern, because parameters are read-only. When a function should change the struct in place, mark the parameter mut:

struct Counter:
    name: str
    count: int

fn tick(c: mut Counter):
    c.count += 1

fn reset(c: mut Counter):
    c.count = 0

fn main():
    visits = Counter("visits", 0)
    visits.tick()
    visits.tick()
    visits.tick()
    print(visits.count)
    reset(&visits)
    print(visits.count)
Output
3
0

With a mut first parameter, visits.tick() is shorthand for tick(&visits). The & says "this call may change visits"; with method syntax the dot plays that role.

Mistakes from other languages

Structs hold data only. Writing a class, or a method with self inside the struct, gets a hint pointing you to plain functions:

Does not compile
struct Rect:
    w, h: float
    fn area(self) float:
        return self.w * self.h

fn main():
    print(Rect(1.0, 2.0))
Compiler output
3: error: expected a name, found 'fn'
3: hint: there is no `self`: take the struct as a normal parameter, `fn area(r: Rect) float:`

== compares two structs field by field (and the arrays and maps inside them element by element), so two points with the same coordinates are equal. When "equal" means something else, such as "the same id", write a function that says so:

struct Point:
    x, y: int

struct User:
    id: int
    name: str

fn same_user(a: User, b: User) bool:
    return a.id == b.id

fn main():
    print(Point(1, 2) == Point(1, 2), Point(1, 2) == Point(2, 1))
    print(User(7, "ada").same_user(User(7, "Ada L.")))
Output
true false
true

A struct can also be a map key: seen: {Point: bool} = {}.

Structs that contain structs

A struct can contain other structs, arrays of structs, and even an array of its own type, which is how you make a tree:

struct Folder:
    name: str
    children: [Folder]

fn count(f: Folder) int:
    n = 1
    for c in f.children:
        n += count(c)
    return n

fn main():
    docs = Folder("docs", [Folder("tour", []), Folder("guides", [])])
    root = Folder("root", [docs, Folder("src", [])])
    print(count(root), "folders")
Output
5 folders

A struct can't contain itself directly (a Folder field inside Folder would be infinitely large). For graphs where nodes point at each other, keep the nodes in an array and store indexes, as shown in the reference.

Try it

Define struct Temperature with a celsius: float field. Write to_fahrenheit(t: Temperature) float (c * 9 / 5 + 32) and warmer(t: Temperature, by: float) Temperature, which returns a new value. Then make a mut version, warm(t: mut Temperature, by: float), and call both styles from main.

Solution

struct Temperature:
    celsius: float

fn to_fahrenheit(t: Temperature) float:
    return t.celsius * 9.0 / 5.0 + 32.0

fn warmer(t: Temperature, by: float) Temperature:
    return Temperature(t.celsius + by)

fn warm(t: mut Temperature, by: float):
    t.celsius += by

fn main():
    today = Temperature(20.0)
    tomorrow = today.warmer(5.0)
    print(today.to_fahrenheit(), tomorrow.to_fahrenheit())
    today.warm(10.0)
    print(today.celsius, today.to_fahrenheit())
Output
68.0 77.0
30.0 86.0

Next: 6. Arrays and maps. Reference: §7 Structs.

Source: docs/tour/05-structs.md. Every example on this page is compiled and run by tern x test docs.