Struct Embedding in Clojure
Clojure supports the concept of protocols and records, which can be used to achieve composition similar to struct embedding in other languages. This example demonstrates how to use these features to create a similar structure and behavior.
When creating records with literals, we initialize the embedding explicitly. In this case, we create a Base
instance and pass it to the Container
constructor.
The Container
record includes a Base
instance, allowing us to access its fields through the Container
. We can also directly invoke methods (in this case, the describe
function) that were defined for Base
on a Container
instance.
The Describer
protocol is used to define a common interface, which both Base
and Container
implement. This demonstrates how Clojure can achieve behavior similar to interface implementation through embedding.
To run this program, save it as struct_embedding.clj
and use:
This example showcases how Clojure can use records and protocols to achieve composition and interface-like behavior, similar to struct embedding in other languages.