Struct Embedding in Crystal
Crystal supports embedding of structs to express a more seamless composition of types. This is similar to inheritance but with some key differences.
To run the program:
In Crystal, we use the include
keyword to mix in modules or classes, which is similar to embedding in other languages. The property
macro is used to create getter and setter methods for instance variables.
Crystal doesn’t have interfaces, but we can use abstract classes or modules to achieve similar behavior. In this example, we’ve used an abstract class Describer
to demonstrate a concept similar to interfaces.
The syntax for creating and using structs (or classes in this case) is quite similar to the original, with some Crystal-specific adjustments. The as
keyword is used for type casting, which is necessary when assigning a Container
instance to a Describer
variable.
Crystal’s type system is more strict than some other languages, so type annotations are often necessary. However, in many cases, Crystal can infer types, making the code cleaner and more concise.