Struct Embedding in Chapel

Chapel supports embedding of classes to express a more seamless composition of types. This is similar to inheritance in other object-oriented languages.

use IO;

class Base {
    var num: int;

    proc describe() {
        return "base with num=" + num:string;
    }
}

// A Container "embeds" a Base. In Chapel, this is achieved through inheritance.
class Container : Base {
    var str: string;
}

proc main() {
    // When creating instances, we initialize the inherited fields explicitly
    var co = new Container(num=1, str="some name");

    // We can access the base's fields directly on co, e.g. co.num
    writeln("co={num: ", co.num, ", str: ", co.str, "}");

    // We can also access the inherited fields using the this keyword
    writeln("also num: ", co.num);

    // Since Container inherits from Base, the methods of Base 
    // also become methods of Container. Here we invoke a method 
    // that was inherited from Base directly on co.
    writeln("describe: ", co.describe());

    // Chapel doesn't have interfaces, but we can achieve similar functionality
    // using abstract classes or by duck typing.
    proc printDescription(obj) {
        writeln("describer: ", obj.describe());
    }

    // We can pass our Container instance to a function expecting
    // an object with a describe() method
    printDescription(co);
}

To run the program, save it as struct_embedding.chpl and use the Chapel compiler:

$ chpl struct_embedding.chpl -o struct_embedding
$ ./struct_embedding
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

In this Chapel version, we use inheritance to achieve a similar effect to Go’s struct embedding. The Container class inherits from the Base class, allowing it to access all of Base’s fields and methods.

Chapel doesn’t have interfaces, but we can achieve similar functionality using abstract classes or by relying on duck typing. In this example, we’ve used a generic function printDescription that can work with any object that has a describe() method.

This demonstrates how Chapel can express concepts similar to Go’s struct embedding, albeit with some differences due to its object-oriented nature.