Struct Embedding in Groovy

Our example demonstrates struct embedding in Groovy. While Groovy doesn’t have a direct equivalent to Go’s struct embedding, we can achieve similar functionality using composition and delegation.

class Base {
    int num

    String describe() {
        "base with num=${num}"
    }
}

class Container {
    Base base
    String str

    Container(int num, String str) {
        this.base = new Base(num: num)
        this.str = str
    }

    // Delegate the describe method to the base object
    String describe() {
        base.describe()
    }
}

// Define an interface
interface Describer {
    String describe()
}

// Main execution
def co = new Container(1, "some name")

println "co={num: ${co.base.num}, str: ${co.str}}"
println "also num: ${co.base.num}"
println "describe: ${co.describe()}"

// Container implements Describer interface implicitly
Describer d = co
println "describer: ${d.describe()}"

In this Groovy example, we create a Base class with a num property and a describe() method. The Container class has a Base object as a property, along with an additional str property.

When creating instances, we initialize the Base object within the Container constructor:

def co = new Container(1, "some name")

We can access the base’s fields through the base property of Container:

println "co={num: ${co.base.num}, str: ${co.str}}"
println "also num: ${co.base.num}"

To mimic Go’s method embedding, we delegate the describe() method in Container to the base object:

String describe() {
    base.describe()
}

This allows us to call describe() directly on a Container instance:

println "describe: ${co.describe()}"

Groovy uses duck typing, so our Container class implicitly implements the Describer interface because it has a describe() method:

Describer d = co
println "describer: ${d.describe()}"

This example demonstrates how to achieve similar functionality to Go’s struct embedding in Groovy using composition and delegation. While the syntax and approach differ, the core concept of composing types and sharing behavior is preserved.