We’ve already used traits extensively in previous chapters. When we implemented BaseMap and Algorithm2D in Supporting Pathfinding with Traits, we consumed the associated traits. It’s time to learn about the inner workings of traits by making one of our own.

Traits provide an interface and describe the functions that must be implemented by a trait consumer. Traits can also specify constraints to ensure that types that implement our trait are compatible with their intended use.

Traits are very powerful, especially when working with a team or shipping a library. By requiring that all consumers of a trait provide a known interface, we can seamlessly switch between traits without changing the code that calls it. We’ll turn map building into a trait and use that trait to expose several algorithms to design maps. This will give us substitutable map builders, allowing us to add more or change up our map design.

The first step is to divide map_builder into a directory-based module that supports sub-modules. Rather than cramming all of our builders into one map_builder.rs file, this makes it easy to find the code for each builder.

Get hands-on with 1200+ tech skills courses.