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.

The Box structure can be used to store objects as traits on the heap. This allows to use polymorphism on objects that can be owned by other objects, instead of borrowing them.

Let us create a Shape trait for which we declare an area() method:

We define two structs Circle and Rectangle:

And implement the Shape trait for both structures:

The two instances we create now can be seen as shapes using their common Shape trait:

One way to show this, is to build a vector of Shape references that mixes a Rectangle and a Circle objects, and then to loop on the vector’s items and use the Shape’s method on them:

Area: 12.566370614359172
Area: 12
()

However we are limited by the fact that these are only references, meaning their lifetime depends on the lifetime of the original objects that reside on the stack. What if we want to move these objects altogether to another data structure on the heap? Using the Box structure we can move objects that have a common trait.

Here is again a vector of Shape objects, but this time we use a Box to store them:

We can access them the same way:

Area: 12.566370614359172
Area: 12
()