Implementing Traits
Speaker Notes
-
To implement
Trait
forType
, you use animpl Trait for Type { .. }
block. -
Unlike Go interfaces, just having matching methods is not enough: a
Cat
type with atalk()
method would not automatically satisfyPet
unless it is in animpl Pet
block. -
Traits may provide default implementations of some methods. Default implementations can rely on all the methods of the trait. In this case,
greet
is provided, and relies ontalk
. -
Multiple
impl
blocks are allowed for a given type. This includes both inherentimpl
blocks and traitimpl
blocks. Likewise multiple traits can be implemented for a given type (and often types implement many traits!).impl
blocks can even be spread across multiple modules/files.