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.
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:
We can access the base’s fields through the base
property of Container
:
To mimic Go’s method embedding, we delegate the describe()
method in Container
to the base
object:
This allows us to call describe()
directly on a Container
instance:
Groovy uses duck typing, so our Container
class implicitly implements the Describer
interface because it has a describe()
method:
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.