Structs in Chapel

Here is the translation of the code example into Chapel:

Structs in Chapel

Chapel’s record is a typed collection of fields. They’re useful for grouping data together to form records.

record Person {
    var name: string;
    var age: int;
}

proc newPerson(name: string): owned Person {
    var p = new owned Person(name = name);
    p.age = 42;
    return p;
}

proc main() {
    // This syntax creates a new struct.
    writeln(new Person("Bob", 20));

    // You can name the fields when initializing a struct.
    writeln(new Person(name = "Alice", age = 30));

    // Omitted fields will be zero-valued.
    writeln(new Person(name = "Fred"));

    // `new owned` yields a pointer to the struct.
    var ann = new owned Person(name = "Ann", age = 40);
    writeln(ann);

    // It's idiomatic to encapsulate new struct creation in constructor functions.
    writeln(newPerson("Jon"));

    // Access struct fields with a dot.
    var s = new Person(name = "Sean", age = 50);
    writeln(s.name);

    // Struct are still mutable
    var sp = s;
    writeln(sp.age);
    sp.age = 51;
    writeln(sp.age);

    // Anonymous struct type usage
    var dog = new record {
        var name: string;
        var isGood: bool;
    }("Rex", true);
    
    writeln(dog);
}

main();

Output when running the above Chapel code:

$ chapel structs.chpl
$ ./structs
{Bob, 20}
{Alice, 30}
{Fred, 0}
{Ann, 40}
{Jon, 42}
Sean
50
51
{Rex, true}

Next example: Methods.