Skip to content
Select theme

Traits

A trait is a set of behaviour a type promises to provide, checked when you compile. Most of this chapter is the small number of traits you meet every day, and the rules around implementing them.

The marker traits — Copy, Send, Sync, Sized — get their own articles because their absence produces errors naming something you never wrote.

Nothing published in this chapter yet — all 18 articles are still to come.

Coming up (18)
  • What is a trait?shared behaviour, checked at compile time
  • What is the difference between a trait and an interface?default methods, associated types, coherence
  • What is the orphan rule?why you cannot implement Display for Vec
  • How to use default implementations in a traitbehaviour that is opt-in to override
  • What are trait bounds?generic code that says what it needs
  • What are associated types?Iterator::Item, and why not a generic
  • What is the Drop trait, and when does it run?deterministic cleanup, and drop order
  • What is the difference between Clone and Copy?explicit and cheap versus implicit
  • What are the Send and Sync marker traits?the two auto traits behind every thread error
  • What is the Sized marker trait?why T is Sized unless you say otherwise
  • What is the difference between PartialEq and Eq?floats, NaN, and HashMap keys
  • Why can’t I derive Eq for a struct with a float?NaN again, and the workaround
  • What are the Deref and DerefMut traits?the coercion that makes &String work as &str
  • What is AsRef used for?accepting many reference types in a signature
  • What is the difference between AsRef, Borrow, and Deref?three conversions that look alike
  • How to implement FromStr so parse() worksone trait method, and a real error type
  • What are supertraits?requiring one trait to use another
  • How to write a trait with one required methodthe design pattern Trait::Item uses