Derives: Custom behavior (reference)¶
This page specifies the dunder methods that define behavior a derive would otherwise provide. The derive catalog is in Derives and traits; the dunders of the arithmetic, bitwise and indexing operators are in Operator traits.
Dunders¶
| Dunder | Signature | Defines | Matching derive |
|---|---|---|---|
__str__ |
(self) -> str |
{value}, str(value), print(value) |
Display |
__eq__ |
(self, other: Self) -> bool |
== |
Eq |
__ne__ |
(self, other: Self) -> bool |
!= |
Eq |
__lt__ |
(self, other: Self) -> bool |
< |
Ord |
__le__ |
(self, other: Self) -> bool |
<= |
Ord |
__gt__ |
(self, other: Self) -> bool |
> |
Ord |
__ge__ |
(self, other: Self) -> bool |
>= |
Ord |
- A dunder in the table is declared with its signature; one declared with another signature, including a
mut selfreceiver, is refused (INCAN-T0001).otheris writtenSelfor as the declaring type with its own type parameters. - Each dunder defines only its own operator. Adopting
std.derives.comparison.Eqsupplies__ne__from__eq__, and adoptingstd.derives.comparison.Ordsupplies__le__,__gt__and__ge__from__lt__and__eq__(see Comparison). - A type does not both define a dunder in the table and derive its matching derive; such a type is refused (
INCAN-T0001).PartialEqmatches asEqdoes andPartialOrdasOrddoes, and a derive matches whether it is written in@derive(...), implied by another derive (OrdimpliesEq) or spelled in@rust.derive(...). Debug,Clone,Copy,DefaultandHashhave no dunder. A method named__hash__is an ordinary method: it does not provideHash, and a set or dict does not call it.
See also¶
- Customize derived behavior (how-to)
- Reflection, for
__fields__()and__class_name__()