7 Traits: Making different types do the same thing

 

This chapter covers

  • The basics of how to write your own traits
  • Method signatures in traits
  • More complex trait examples
  • The From trait
  • The orphan rule—what you’re allowed to implement a trait on
  • Taking a String or a &str in a function

We’ve touched on traits a little bit here and there in the book so far, but now it’s time to give them some needed attention. Understanding traits and how they work will let us give traits to our own types and even make our own.

7.1 Traits: The basics

We have seen traits before: Debug, Copy, and Clone are all traits. The easiest way to think of traits is as powers or qualifications. If a type has a trait, it can do things it couldn’t do before. Also, if a type has a trait, you can guarantee to the compiler that it can do something—no matter what type it is.

To give a trait to a type, you have to implement that trait for that type. “Type X implements Trait Y” means that Type X definitely has the methods of Trait Y. Type X can have its own separate methods, too, and Type X might implement other traits as well. A human equivalent would be that Person X might decide to take the bar exam to become a lawyer. But Person X might have other qualifications, too, and might have other personal skills, such as being able to type really fast.

7.1.1 All you need are the method signatures

7.1.2 More complex examples

7.1.3 Traits as bounds

7.1.4 Traits are like qualifications

7.2 The From trait

7.3 The orphan rule

7.4 Getting around the orphan rule with newtypes

sitemap