Creating Traits

You’ve already used traits a lot in previous chapters. When you implemented BaseMap and Algorithm2D in Supporting Pathfinding with Traits, you consumed the associated traits. It’s time to learn about the inner workings of traits by making one of your own.

Traits provide an interface and describe the functions that a trait consumer must implement. Traits can also specify constraints to ensure that types that implement your 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, you can seamlessly switch between traits without changing the code that calls it. You’re going to turn map ...

Get Hands-on Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.