Structs, enums and case

View source

Group values with struct, list the possible forms of a value with enum, and take them apart with case.

So far each variable held one number or one piece of text. Real programs need to keep several values together, and to say that a value is one of a few possible kinds. A struct does the first. An enum does the second. case is how you look at an enum.

Structs

A struct is a record with named fields. Declare it outside any verb. Each field has a name and a type:

actus
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 3,
        y: 4,
    };
    point.x = 10;
    println(int: point.x);
    println(int: point.y);
    println(int: sum(point: abs point));
}

verb sum(abs point: Point) -> Int {
    return point.x + point.y;
}
bash
actus run
text
10
4
14
process exited with status 0

Read the program from the top:

  • struct Point { x: Int, y: Int, } declares the type.
  • Point { x: 3, y: 4, } creates a value. You write every field, with its name.
  • point.x reads a field, and point.x = 10; changes it. You can change fields because point is an erg variable.
  • sum(point: abs point) hands the whole struct to a verb that only reads it. The verb reads point.x and point.y the same way.

The compiler checks that you fill in every field and that you only use fields that exist:

actus
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 1,
    };
    println(int: point.x);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1032] at 7:24: missing field `y` in `Point` initializer
actus
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 1,
        y: 2,
    };
    println(int: point.z);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1031] at 11:18: unknown field `z` on struct `Point`

A struct is not a number, so it is not copied when you assign it to a new variable: it moves. This is true even when all its fields are plain numbers. After erg other = point; the name point is gone.

actus
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 1,
        y: 2,
    };
    erg other = point;
    println(int: point.x);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1005] at 12:18: use of moved binding `point`

Copying a struct

If you need two separate points, the struct must say that it may be copied. Write meta copy above its declaration, and write each copy yourself with copy. No copy ever happens without a copy in the source:

actus
meta copy
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 1,
        y: 2,
    };
    erg other = copy(value: abs point);
    point.x = 10;
    println(int: point.x);
    println(int: other.x);
}
bash
actus run
text
10
1
process exited with status 0

other is a new Point, and changing point does not change it. Without meta copy, the same copy is an error:

actus
struct Point {
    x: Int,
    y: Int,
}

verb main() {
    erg point: Point = Point {
        x: 1,
        y: 2,
    };
    erg other = copy(value: abs point);
    println(int: other.x);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1021] at 11:33: invalid `value` argument in intrinsic `copy`

meta copy is only accepted when every field can be copied: a number, a Bool, a float, or another meta copy type. A struct with a String field cannot be meta copy. Enums work the same way.

Enums

An enum is a value that is exactly one of a fixed list of variants. A traffic light is red, yellow or green, and never two of them at once:

actus
enum Light {
    Red,
    Yellow,
    Green,
}

verb main() {
    erg light: Light = Light.Yellow;
    erg wait = case light {
        Light.Red => 30,
        Light.Yellow => 5,
        Light.Green => 25,
    };
    println(int: wait);
}
bash
actus run
text
5
process exited with status 0

You write a variant as the enum name, a dot and the variant name: Light.Yellow. case looks at the value and runs the arm that matches. Here case is used as a value, like if in Conditions and loops. Each arm is pattern => result, and the arms are separated by commas.

Variants that carry data

A variant can carry values. There are three kinds in one enum below:

  • Dot carries nothing.
  • Square(Int) carries one Int.
  • Rect {width: Int, height: Int} carries named fields.
actus
enum Shape {
    Dot,
    Square(Int),
    Rect {width: Int, height: Int},
}

verb main() {
    erg dot: Shape = Shape.Dot;
    erg square: Shape = Shape.Square(4);
    erg rect: Shape = Shape.Rect(width: 3, height: 5);
    println(int: area(shape: abs dot));
    println(int: area(shape: abs square));
    println(int: area(shape: abs rect));
}

verb area(abs shape: Shape) -> Int {
    return case shape {
        Shape.Dot => 0,
        Shape.Square(side) => side * side,
        Shape.Rect {width: w, height: h} => w * h,
    };
}
bash
actus run
text
0
16
15
process exited with status 0

You build a variant with data like a call: Shape.Square(4), or with the field names, Shape.Rect(width: 3, height: 5). In case, a pattern gives names to the data it holds. Shape.Square(side) names the number side for that arm. Shape.Rect {width: w, height: h} names the two fields w and h.

case must cover every possibility

case has to handle every variant. If you forget one, the program does not compile, and the message names the missing variant:

actus
enum Light {
    Red,
    Yellow,
    Green,
}

verb main() {
    erg light: Light = Light.Red;
    erg wait = case light {
        Light.Red => 30,
        Light.Yellow => 5,
    };
    println(int: wait);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1045] at 9:16: non-exhaustive match on `Light`; missing: Green

This is the main reason to use an enum. When you add a new variant later, the compiler shows you every case that needs a new arm.

The wildcard

To cover all the remaining possibilities at once, use _. It matches anything. This also lets you use case on numbers:

actus
verb main() {
    erg a = 1;
    erg b = 50;
    println(int: size(n: abs a));
    println(int: size(n: abs b));
}

verb size(abs n: Int) -> Int {
    return case n {
        0 => 0,
        1 => 1,
        _ => 2,
    };
}
bash
actus run
text
1
2
process exited with status 0

Arms are tried from the top. An arm after _ could never run, so the compiler rejects it. Put _ last.

case on a Bool

A Bool has two values, so true and false cover everything and you do not need _:

actus
verb main() {
    erg ready = true;
    erg code = case ready {
        true => 1,
        false => 0,
    };
    println(int: code);
}
bash
actus run
text
1
process exited with status 0

If an arm is missing, the message names the value:

actus
verb main() {
    erg ready = true;
    erg code = case ready {
        true => 1,
    };
    println(int: code);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1045] at 3:16: non-exhaustive match on `Bool`; missing: false

A _ after both values can never match, so it is an error. The same is true for a _ after arms that already name every variant of an enum:

actus
verb main() {
    erg ready = true;
    erg code = case ready {
        true => 1,
        false => 0,
        _ => 2,
    };
    println(int: code);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1046] at 6:9: unreachable pattern `_`

Numbers have too many values to list, so a case on a number always needs _, as in the example before.

Guards

An arm can have a condition. Write if after the pattern. The arm is used only when the pattern matches and the condition is true:

actus
enum Reading {
    Missing,
    Value(Int),
}

verb main() {
    erg high: Reading = Reading.Value(150);
    erg low: Reading = Reading.Value(5);
    erg none: Reading = Reading.Missing;
    println(int: classify(reading: abs high));
    println(int: classify(reading: abs low));
    println(int: classify(reading: abs none));
}

verb classify(abs reading: Reading) -> Int {
    return case reading {
        Reading.Value(v) if v > 100 => 2,
        Reading.Value(_) => 1,
        Reading.Missing => 0,
    };
}
bash
actus run
text
2
1
0
process exited with status 0

Reading.Value(v) if v > 100 catches large readings. A reading of 5 does not pass the guard and falls to the next arm, Reading.Value(_). The _ inside the parentheses means "there is a value, and I do not need it".

case as a statement

case does not need to produce a value. Used as a statement, each arm does something and the whole case ends with a semicolon. The same program also shows that two values of a plain enum, one without data, can be compared with == and !=:

actus
enum Light {
    Red,
    Green,
}

verb main() {
    erg now: Light = Light.Red;
    erg next: Light = Light.Green;
    if now == next {
        println(string: "same");
    } else {
        println(string: "different");
    }
    case now {
        Light.Red => println(string: "stop"),
        Light.Green => println(string: "go"),
    };
}
bash
actus run
text
different
stop
process exited with status 0

Enums that carry data cannot be compared with == as a whole. Take them apart with case instead.

What you learned

  • struct Name { field: Type, } groups named values. Create one with every field, read and change fields with a dot.
  • enum Name { A, B(Int), C {x: Int}, } lists the possible forms of a value.
  • case matches a value against patterns, binds the data inside a variant, and must cover every possibility. _ matches the rest, and if adds a condition.
  • Assigning a struct to a new variable moves it. A struct declared with meta copy can be copied, and the copy is written as copy(value: abs x).
  • A case on a Bool is complete with true and false. A _ after every value is an error.

Next: Ownership roles.