Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

It is possible to use a trait as a field’s type inside a structure. This allows to store in this field any object whose type implements the trait. To do that we need:

As an example, we will use a structure for a drawing in which we store a single shape as a trait. The trait provides a draw() method that we will use to simulate the drawing on screen.

Let us start with the trait definition:

We define a Rectangle structure:

With its implementation of the Shape trait that just prints a message:

We now define a structure Drawing that stores a single shape as a trait:

We implement a draw() method for it that calls the draw() method of the Shape object:

Let us instantiate a Rectangle object:

We also instantiate a Drawing object using our Rectangle object for the field’s value. The draw() method of Drawing calls the draw() method of the Shape object without knowing anything about its concrete type:

Drawing rectangle 20x30 at (4, 6).
()

see solution