liveBook · Manning

Trait implementation

As explained in Idiomatic Rust

A trait implementation is a declaration that a Rust type satisfies a trait and provides its required behavior.

A trait implementation declares that a type provides a trait’s behavior. Unlike inheritance, traits connect types through the capabilities they implement; a trait can apply to different types, subject to any required trait bounds. section 2.2.2 section 2.2

trait DoesItBark {                     #1
    fn it_barks(&self) -> bool;        #2
}

struct Dog;

impl DoesItBark for Dog {              #3
    fn it_barks(&self) -> bool {
        true                           #4
    }
}

A minimal example defines a barking capability and implements it for Dog by supplying the required method. section 2.2.2

Choose how to provide the implementation:

  • Use #[derive] for supported common traits such as Clone, Debug, and Default; it supplies implementations with little boilerplate. section 2.2.5
  • Write an impl yourself when the behavior should differ from the derived default. For example, a custom Default implementation can create a Pumpkin with chosen field values. section 2.2.5
  • Rust does not allow implementing a trait for a type outside your crate; this restriction prevents conflicting implementations from different crates. section 7.2

How Idiomatic Rust covers it

How deep it goes
Explains basic implementation syntax, derivation, and a crate boundary restriction, while deferring blanket implementations to later discussion.
Examples
Demonstrates a Dog implementing a barking method and a Pumpkin using derived or custom Clone, Debug, and Default implementations.
What it assumes
Explains traits and implementations from their basic definitions, without stating assumed background knowledge.
What you can do after
Build a type’s trait behavior by writing an implementation or applying #[derive] for supported traits.
How it connects
Links implementations to traits, generics, trait bounds, blanket implementations, and the derive attribute.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.