Struct Embedding in Dart
Dart supports composition of classes through mixins and inheritance, which can be used to achieve a similar effect to struct embedding in other languages. This example demonstrates how to use these features to create a more seamless composition of types.
To run the program, save it as class_composition.dart
and use the dart
command:
In this Dart example:
We define a
Base
class with anum
property and adescribe()
method.Instead of struct embedding, we use a mixin to include
Base
inContainer
. This allowsContainer
to inherit the properties and methods ofBase
.We create an instance of
Container
, initializing both its own property (str
) and the mixin’s property (num
).We can access the mixin’s properties and methods directly on the
Container
instance.We define an interface
Describer
with adescribe()
method. BecauseContainer
includes theBase
mixin which has this method, it automatically implements this interface.We demonstrate that a
Container
instance can be assigned to aDescriber
variable, showing that it indeed implements the interface.
This approach in Dart achieves a similar effect to struct embedding, allowing for composition of types and implicit interface implementation. However, it’s important to note that Dart’s approach using mixins and inheritance has some differences in behavior and limitations compared to Go’s struct embedding.