Rust's trait system does not allow orphans: roughly, every impl
`impl` must live
either in the crate that defines the trait or the implementing
type. Consequently, crates that define new types should eagerly implement all
applicable, common traits.
To see why, consider the following situation:
std
`stddefines trait
` defines trait Show
`Show`.url
`urldefines type
` defines type Url
`Url, without implementing
`, without implementing Show
`Show`.webapp
`webappimports from both
` imports from both std
`stdand
` and url
`url`,There is no way for webapp
`webappto add
` to add Show
`Showto
` to url
`url`, since it defines neither.
(Note: the newtype pattern can provide an efficient, but inconvenient
workaround; see newtype for views)
The most important common traits to implement from std
`std` are:
Clone, Show, Hash, Eq
Send
`Sendand
` and Share
`Share`. [FIXME][FIXME]. This guideline is in flux while the "opt-in" nature of built-in traits is being decided. See https://github.com/rust-lang/rfcs/pull/127
Deriving saves implementation effort, makes correctness trivial, and automatically adapts to upstream changes.
Operators with built in syntax (*
`*,
`, |
`|, and so on) can be provided for a type by implementing the traits in
`, and so on) can be provided for a type
by implementing the traits in core::ops
`core::ops. These operators come with strong expectations: implement
`. These operators come with strong
expectations: implement Mul
`Mul` only for an operation that bears some resemblance
to multiplication (and shares the expected properties, e.g. associativity), and
so on for the other traits.
Drop
`Drop` traitThe Drop
`Drop` trait is treated specially by the compiler as a way of
associating destructors with types. See
the section on destructors for
guidance.
Deref
`Deref/
`/DerefMut
`DerefMut` traitsDeref
`Deref/
`/DerefMut
`DerefMut` only for smart pointers. [FIXME: needs RFC]The Deref
`Deref` traits are used implicitly by the compiler in many circumstances,
and interact with method resolution. The relevant rules are designed
specifically to accommodate smart pointers, and so the traits should be used
only for that purpose.
Deref
`Deref/
`/DerefMut
`DerefMut` implementation. [FIXME: needs RFC]Because the Deref
`Dereftraits are invoked implicitly by the compiler in sometimes subtle ways, failure during dereferencing can be extremely confusing. If a dereference might not succeed, target the
` traits are invoked implicitly by the compiler in sometimes
subtle ways, failure during dereferencing can be extremely confusing. If a
dereference might not succeed, target the Deref
`Dereftrait as a
` trait as a Result
`Resultor
` or
Option
`Option` type instead.
Deref
`Deref/
`/DerefMut
`DerefMut` [FIXME: needs RFC]The rules around method resolution and Deref
`Derefare in flux, but inherent methods on a type implementing
` are in flux, but inherent methods
on a type implementing Deref
`Deref` are likely to shadow any methods of the referent
with the same name.