Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 9 · Traits & generics

    9.4Standard traits

    The traits from the standard library that make your types printable, comparable, hashable, sortable, convertible and usable with operators, which ones to derive and which to write by hand.

    About 30 minutesIntermediate

    On this page
    1. Concept map
    2. Derive the everyday traits
    3. Display: text for users
    4. Two kinds of equality and ordering
    5. Conversions: From, Into, TryFrom, AsRef
    6. Operators and Deref
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Text for usersA toString() method, used by template literalsOverride ToString()Implement Display; then {} and .to_string() work
    Text for debuggingconsole.log(value), JSON.stringifyA record's generated ToString()#[derive(Debug)]; then {:?} and {:#?}
    Value equality=== compares objects by reference; you write equalsIEquatable<T>, Equals and ==; records generate them#[derive(PartialEq, Eq)]; then ==
    Hash keysMap and Set compare objects by referenceGetHashCode() that agrees with Equals#[derive(Hash)] next to Eq
    Ordering and sortingA compare function passed to sortIComparable<T>, IComparer<T>#[derive(PartialOrd, Ord)]; then <, .sort(), .max()
    ConversionsFunctions you write and nameConstructors, implicit and explicit operatorsFrom and Into; TryFrom and TryInto when it can fail

    In TypeScript, each everyday ability of a type works its own way: toString() for text, JSON.stringify for debugging, a hand-written equals, a compare function for sort, and no operator overloading at all.In C#, each everyday ability of a type has its own interface or override: ToString(), IEquatable<T> with GetHashCode(), IComparable<T>, and operator +. Records generate some of them for you. In Rust, they’re all traits from the standard library, and most of them you get with one #[derive(...)] line. This lesson covers the ones you’ll use on almost every type, and when to write one by hand instead. Traits covers how traits themselves work.

    Derive the everyday traits

    Here’s a version number that we compare, sort, deduplicate and give a default value.

    TypeScript
    version.ts
    class Version {
      major: number;
      minor: number;
      patch: number;
      constructor(major: number, minor: number, patch: number) {
        this.major = major;
        this.minor = minor;
        this.patch = patch;
      }
    }
    
    // Each ability is a function you write by hand
    function equals(a: Version, b: Version): boolean {
      return a.major === b.major && a.minor === b.minor && a.patch === b.patch;
    }
    
    function compare(a: Version, b: Version): number {
      return a.major - b.major || a.minor - b.minor || a.patch - b.patch;
    }
    
    function label(v: Version): string {
      return `${v.major}.${v.minor}.${v.patch}`;
    }
    
    const a = new Version(1, 10, 0);
    const b = new Version(a.major, a.minor, a.patch);
    console.log(equals(a, b) ? "equal" : "not equal"); // a === b would be false
    
    const versions = [new Version(2, 0, 0), a, new Version(1, 2, 0), b];
    versions.sort(compare);
    console.log(`sorted: ${versions.map(label).join(", ")}`);
    // A Set compares objects by reference, so deduplicate by a string key
    console.log(`unique: ${new Set(versions.map(label)).size}`);
    console.log(`default: ${label(new Version(0, 0, 0))}`);
    C#
    Version.cs
    var a = new Version(1, 10, 0);
    var b = a; // a record struct, so this is a copy
    Console.WriteLine(a == b ? "equal" : "not equal");
    
    List<Version> versions = [new Version(2, 0, 0), a, new Version(1, 2, 0), b];
    versions.Sort(); // uses IComparable<Version>
    Console.WriteLine($"sorted: {string.Join(", ", versions.Select(Label))}");
    Console.WriteLine($"unique: {new HashSet<Version>(versions).Count}"); // Equals + GetHashCode
    Console.WriteLine($"default: {Label(default)}");
    
    static string Label(Version v) => $"{v.Major}.{v.Minor}.{v.Patch}";
    
    // A record struct generates Equals, GetHashCode, == and ToString. Ordering is up to you.
    readonly record struct Version(int Major, int Minor, int Patch) : IComparable<Version>
    {
        public int CompareTo(Version other) =>
            (Major, Minor, Patch).CompareTo((other.Major, other.Minor, other.Patch));
    }
    Rust
    use std::collections::HashSet;
    
    #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
    struct Version {
        major: u32,
        minor: u32,
        patch: u32,
    }
    
    impl Version {
        fn new(major: u32, minor: u32, patch: u32) -> Self {
            Version {
                major,
                minor,
                patch,
            }
        }
    }
    
    fn label(v: &Version) -> String {
        format!("{}.{}.{}", v.major, v.minor, v.patch)
    }
    
    fn main() {
        let a = Version::new(1, 10, 0);
        let b = a.clone(); // Clone
        println!("{}", if a == b { "equal" } else { "not equal" }); // PartialEq
    
        let mut versions = vec![Version::new(2, 0, 0), a, Version::new(1, 2, 0), b];
        versions.sort(); // Ord
        let labels: Vec<String> = versions.iter().map(label).collect();
        println!("sorted: {}", labels.join(", "));
        let unique: HashSet<Version> = versions.into_iter().collect(); // Eq + Hash
        println!("unique: {}", unique.len());
        println!("default: {}", label(&Version::default())); // Default
    }

    Output

    equal
    sorted: 1.2.0, 1.10.0, 1.10.0, 2.0.0
    unique: 3
    default: 0.0.0

    One line, #[derive(...)], asks the compiler to write eight trait implementations from the fields:

    • Debug: a developer-facing text form, for {:?}, dbg! and failing assert_eq! messages.
    • Clone: .clone() copies the value by cloning each field, so a String or Vec field gets its own new heap buffer. Copy vs. Clone covers it, and when to add Copy.
    • PartialEq and Eq: == and !=, comparing every field.
    • Hash: lets the type be a key in a HashMap or HashSet, together with Eq.
    • PartialOrd and Ord: <, >, .sort(), .max(). Derived ordering compares the fields in the order you declared them, which is exactly right for major, minor, patch.
    • Default: Version::default(), here with every field at 0.

    A derive works only if every field implements the same trait. u32 implements all eight, so Version can derive all eight.

    Where TypeScript gives you === (same object) by default and makes you write value equality yourself, Rust’s == always compares contents (comparing addresses takes an explicit std::ptr::eq), and only types that implement PartialEq have it at all.
    A C# record generates equality, hashing and ToString() for you, but not ordering. Rust’s derives are opt-in one trait at a time, and ordering is one of them.

    Debug output looks like the code that built the value. {:#?} spreads it over several lines:

    println!("{v:?}");
    println!("{v:#?}");

    Output

    Version { major: 1, minor: 10, patch: 0 }
    Version {
        major: 1,
        minor: 10,
        patch: 0,
    }

    Display: text for users

    Debug is for developers, and it’s derived. Text meant for users is Display, and you always write it yourself: there’s no derive, because only you know how your type should read. Implement one method, fmt, and {}, format! and .to_string() all work.

    TypeScript
    display.ts
    class Version {
      major: number;
      minor: number;
      patch: number;
      constructor(major: number, minor: number, patch: number) {
        this.major = major;
        this.minor = minor;
        this.patch = patch;
      }
      toString(): string {
        return `v${this.major}.${this.minor}.${this.patch}`;
      }
    }
    
    const v = new Version(1, 10, 0);
    console.log(`Installed ${v}`);
    const text = v.toString();
    console.log(`${text} has ${text.length} characters`);
    C#
    Display.cs
    var v = new Version(1, 10, 0);
    Console.WriteLine($"Installed {v}");
    var text = v.ToString();
    Console.WriteLine($"{text} has {text.Length} characters");
    
    readonly record struct Version(int Major, int Minor, int Patch)
    {
        public override string ToString() => $"v{Major}.{Minor}.{Patch}";
    }
    Rust
    use std::fmt;
    
    struct Version {
        major: u32,
        minor: u32,
        patch: u32,
    }
    
    impl fmt::Display for Version {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "v{}.{}.{}", self.major, self.minor, self.patch)
        }
    }
    
    fn main() {
        let v = Version {
            major: 1,
            minor: 10,
            patch: 0,
        };
        println!("Installed {v}");
        let text = v.to_string();
        println!("{text} has {} characters", text.len());
    }

    Output

    Installed v1.10.0
    v1.10.0 has 7 characters

    write! works like format!, but writes into the formatter f instead of building a new String. You never implement .to_string() yourself: the standard library implements ToString for every type that implements Display. (Clippy warns if you implement ToString directly.)

    Two kinds of equality and ordering

    Why are there two equality traits, and two ordering traits? Because of floating-point numbers. NaN (“not a number”) isn’t equal to anything, itself included:

    TypeScript
    nan.ts
    const missing = NaN;
    const copy = missing;
    console.log(missing === copy ? "NaN equals itself" : "NaN does not equal itself");
    
    const readings = [21, 19, 23];
    const sorted = readings.toSorted((a, b) => a - b);
    console.log(`sorted: ${sorted.join(", ")}`);
    C#
    Nan.cs
    var missing = double.NaN;
    var copy = missing;
    Console.WriteLine(missing == copy ? "NaN equals itself" : "NaN does not equal itself");
    
    double[] readings = [21, 19, 23];
    Console.WriteLine($"sorted: {string.Join(", ", readings.Order())}");
    Rust
    let missing = f64::NAN;
    let copy = missing;
    if missing == copy {
        println!("NaN equals itself");
    } else {
        println!("NaN does not equal itself");
    }
    
    let mut readings = [21.0, 19.0, 23.0];
    readings.sort_by(f64::total_cmp); // f64 isn't Ord, so say how to compare
    let labels: Vec<String> = readings.iter().map(|r| r.to_string()).collect();
    println!("sorted: {}", labels.join(", "));

    Output

    NaN does not equal itself
    sorted: 19, 21, 23

    Rust encodes that in the types:

    • PartialEq gives you ==. f64 implements it.
    • Eq adds a promise, with no new methods: every value equals itself. f64 can’t make that promise, so it doesn’t implement Eq. HashMap and HashSet keys need Eq (and Hash), so a float can’t be a key.
    • PartialOrd gives you < and >, and partial_cmp, which returns None when two values can’t be compared, like NaN and 1.0.
    • Ord promises that any two values can be compared, through cmp. .sort(), an iterator’s .max() and BTreeMap keys need it, so floats can’t use any of them. Use sort_by(f64::total_cmp), which picks one fixed order for every float, NaN included.

    TypeScript has the same split, hidden in different operators: NaN === NaN is false, but Object.is(NaN, NaN) is true, and a Set or Map treats NaN as equal to itself.C# has the same split, hidden in different methods: double.NaN == double.NaN is false, but double.NaN.Equals(double.NaN) is true, which is what lets NaN be a dictionary key. Rust picks one meaning per trait, and the compiler checks which one a function needs. Ask a float slice to .sort() and it says so:

    let mut readings = [21.0, 19.0, 23.0];
    readings.sort();

    Rust doesn't compile this: error E0277

    error[E0277]: the trait bound `{float}: Ord` is not satisfied
     --> main.rs:2:10
      |
    2 | readings.sort();
      |          ^^^^ the trait `Ord` is not implemented for `{float}`
      |
      = help: the following other types implement trait `Ord`:
                i128
                i16
                i32
                i64
                i8
                isize
                u128
                u16
              and 4 others
    note: required by a bound in `slice::<impl [T]>::sort`

    The rule of thumb for your own types: derive PartialEq and PartialOrd always, and add Eq and Ord (and Hash) whenever no field is a float.

    Conversions: From, Into, TryFrom, AsRef

    Conversions between types are traits too, so they work the same way everywhere:

    • From<T> is a conversion that can’t fail. Implement From<Celsius> for Fahrenheit, and you get Into for free: celsius.into() works wherever the target type is known.
    • TryFrom<T> is a conversion that can fail. It returns a Result, with an error type you choose. You get TryInto for free.
    TypeScript
    convert.ts
    type Celsius = { degrees: number };
    type Fahrenheit = { degrees: number };
    type Percent = { value: number };
    
    function toFahrenheit(c: Celsius): Fahrenheit {
      return { degrees: (c.degrees * 9) / 5 + 32 };
    }
    
    function toPercent(value: number): Percent {
      if (value < 0 || value > 100) {
        throw new RangeError(`${value} is not between 0 and 100`);
      }
      return { value };
    }
    
    const boiling = toFahrenheit({ degrees: 100 });
    console.log(`100 C is ${boiling.degrees} F`);
    for (const input of [80, 150]) {
      try {
        console.log(`volume: ${toPercent(input).value}%`);
      } catch (e) {
        console.log(`error: ${(e as Error).message}`);
      }
    }
    C#
    Convert.cs
    Fahrenheit boiling = new Celsius(100); // implicit: it can't fail
    Console.WriteLine($"100 C is {boiling.Degrees} F");
    foreach (var input in new[] { 80, 150 })
    {
        try
        {
            var volume = (Percent)input; // explicit: it can throw
            Console.WriteLine($"volume: {volume.Value}%");
        }
        catch (InvalidCastException e)
        {
            Console.WriteLine($"error: {e.Message}");
        }
    }
    
    readonly record struct Fahrenheit(double Degrees);
    
    readonly record struct Celsius(double Degrees)
    {
        public static implicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32);
    }
    
    readonly record struct Percent(int Value)
    {
        public static explicit operator Percent(int value) =>
            value is >= 0 and <= 100
                ? new Percent(value)
                : throw new InvalidCastException($"{value} is not between 0 and 100");
    }
    Rust
    struct Celsius(f64);
    struct Fahrenheit(f64);
    
    impl From<Celsius> for Fahrenheit {
        fn from(c: Celsius) -> Self {
            Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
        }
    }
    
    struct Percent(u8);
    
    impl TryFrom<i32> for Percent {
        type Error = String;
    
        fn try_from(value: i32) -> Result<Self, Self::Error> {
            match u8::try_from(value) {
                Ok(v) if v <= 100 => Ok(Percent(v)),
                _ => Err(format!("{value} is not between 0 and 100")),
            }
        }
    }
    
    fn main() {
        let boiling: Fahrenheit = Celsius(100.0).into(); // From gives you Into
        println!("100 C is {} F", boiling.0);
        for input in [80, 150] {
            match Percent::try_from(input) {
                Ok(volume) => println!("volume: {}%", volume.0),
                Err(message) => println!("error: {message}"),
            }
        }
    }

    Output

    100 C is 212 F
    volume: 80%
    error: 150 is not between 0 and 100

    The standard library uses the same traits for numbers: i64::from(5_i32) can’t fail, so it’s From; u8::try_from(value) can, so it’s TryFrom, as used inside try_from above. The ? operator calls From to convert one error type into another, which Result and the ? operator shows. Implement From rather than Into: From gives you Into for free, but not the other way around, and Clippy flags a hand-written Into (from_over_into).

    C# splits conversions the same way, by convention: an implicit operator shouldn’t fail, an explicit one may throw. Rust’s difference is that TryFrom returns a Result, so the caller can’t forget the failure case, and that nothing converts without a visible .into() or from call.

    AsRef<T> is a cheap borrow-conversion: “anything I can view as a &T”. It’s how one function can accept several kinds of argument without taking ownership. The standard library’s fs::read_to_string takes any path type that implements AsRef<Path>, so you can pass a &str, a String or a PathBuf:

    fn shout(text: impl AsRef<str>) -> String {
        text.as_ref().to_uppercase()
    }
    
    fn main() {
        let owned = String::from("hello");
        println!("{}", shout("hi"));
        println!("{}", shout(&owned));
        println!("{}", shout(owned));
    }

    Output

    HI
    HELLO
    HELLO

    For your own functions, a plain &str parameter is usually enough, since &String converts to it automatically. Reach for AsRef when you want to accept owned and borrowed values alike.

    Operators and Deref

    Rust’s operators are traits in std::ops. a + b calls Add::add(a, b), a += b calls AddAssign, -a calls Neg, a[i] calls Index. Implement the trait, and the operator works on your type. (== and < come from PartialEq and PartialOrd, above.) TypeScript has no operator overloading, so the closest thing is a method like plus.It’s C#‘s operator +, written as a trait implementation.

    TypeScript
    point.ts
    class Point {
      x: number;
      y: number;
      constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
      }
      plus(other: Point): Point {
        return new Point(this.x + other.x, this.y + other.y);
      }
    }
    
    const sum = new Point(1, 2).plus(new Point(3, 4));
    console.log(`(${sum.x}, ${sum.y})`);
    let total = new Point(10, 10);
    total = total.plus(sum);
    console.log(`(${total.x}, ${total.y})`);
    C#
    Point.cs
    var sum = new Point(1, 2) + new Point(3, 4);
    Console.WriteLine($"({sum.X}, {sum.Y})");
    var total = new Point(10, 10);
    total += sum; // C# builds += from +
    Console.WriteLine($"({total.X}, {total.Y})");
    
    readonly record struct Point(int X, int Y)
    {
        public static Point operator +(Point a, Point b) => new(a.X + b.X, a.Y + b.Y);
    }
    Rust
    use std::ops::{Add, AddAssign};
    
    #[derive(Debug, Clone, Copy, PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    impl Add for Point {
        type Output = Point;
    
        fn add(self, other: Point) -> Point {
            Point {
                x: self.x + other.x,
                y: self.y + other.y,
            }
        }
    }
    
    impl AddAssign for Point {
        fn add_assign(&mut self, other: Point) {
            self.x += other.x;
            self.y += other.y;
        }
    }
    
    fn main() {
        let sum = Point { x: 1, y: 2 } + Point { x: 3, y: 4 };
        println!("({}, {})", sum.x, sum.y);
        let mut total = Point { x: 10, y: 10 };
        total += sum; // needs AddAssign
        println!("({}, {})", total.x, total.y);
    }

    Output

    (4, 6)
    (14, 16)

    add takes self by value, so a + b moves both operands. That’s free for a small Copy type like Point. For a large type, implement Add for references too (impl Add for &Matrix) so &a + &b leaves both alive. You can’t invent new operators, and &&, || and = can’t be overloaded.

    Deref is the trait behind * and behind automatic conversions such as &String to &str, &Vec<T> to &[T] and &Box<T> to &T. When you call a method, Rust follows Deref until it finds the method, which is why boxed.len() works on a Box<String>. Implement it for your own smart pointers and thin wrappers that should act like the value they hold, and almost nowhere else; the pitfalls below show why.

    Which one should I use?

    WhatWhenWhyHow
    DebugEvery type you define.{:?}, dbg! and failing assert_eq! need it, and so do unwrap messages.#[derive(Debug)]
    Clone (+ Copy)Most data types. Add Copy only for small types with no heap data..clone() for explicit copies; Copy makes assignment copy instead of move.#[derive(Clone)], #[derive(Clone, Copy)]
    PartialEqComparing values with == makes sense.==, assert_eq!, .contains().Derive. Write it by hand to ignore a field or compare differently.
    Eq + HashNo field is a float, and the type may be a map or set key.HashMap and HashSet keys need both.Derive them together. Hand-write them only together.
    PartialOrd + OrdThe type has a natural order: versions, dates, priorities.<, .sort(), .max(), BTreeMap keys.Derive when declaration order is the right priority; otherwise implement cmp by hand.
    DefaultThere’s an obvious starting value.T::default(), ..Default::default(), .unwrap_or_default().Derive; on an enum, mark one unit variant #[default].
    DisplayUsers will read the value.{} and .to_string().Implement fmt by hand; there’s no derive.
    From / TryFromOne type converts to another: From if it can’t fail, TryFrom if it can..into(), T::from(x), and error conversion with ?.impl From<Celsius> for Fahrenheit; never implement Into directly.
    AsRef<T>A parameter should accept owned and borrowed forms alike.One function for &str, String and more, without taking ownership.fn shout(text: impl AsRef<str>)
    Add, Mul, …Math-like types: vectors, money, matrices.a + b reads better than a.plus(b).impl Add for Point with type Output.
    DerefRarely: your type is a smart pointer or a thin wrapper that should act like its contents.Method calls and & conversions reach the inner value.impl Deref for Wrapper { type Target = Inner; ... }. Never for inheritance.

    Rule of thumb: put #[derive(Debug, Clone, PartialEq)] on every data type you define. Add Eq and Hash when no field is a float, PartialOrd and Ord when the field order is the natural order, Copy for small plain values, and Default when “empty” or “zero” makes sense. Implement Display and From by hand. Write a derivable trait by hand only when the derived version would be wrong: when equality should ignore a field, or sorting should use a different order than the fields.

    Under the hood

    A derive writes ordinary code. Here’s roughly what #[derive(PartialEq, Eq, PartialOrd, Ord)] writes for Version:

    use std::cmp::Ordering;
    
    struct Version {
        major: u32,
        minor: u32,
        patch: u32,
    }
    
    impl PartialEq for Version {
        fn eq(&self, other: &Self) -> bool {
            self.major == other.major && self.minor == other.minor && self.patch == other.patch
        }
    }
    
    impl Eq for Version {}
    
    impl Ord for Version {
        // Compare field by field; the first difference decides
        fn cmp(&self, other: &Self) -> Ordering {
            self.major
                .cmp(&other.major)
                .then(self.minor.cmp(&other.minor))
                .then(self.patch.cmp(&other.patch))
        }
    }
    
    impl PartialOrd for Version {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }
    
    fn main() {
        let old = Version {
            major: 1,
            minor: 2,
            patch: 0,
        };
        let new = Version {
            major: 1,
            minor: 10,
            patch: 0,
        };
        println!("{}", old < new);
    }

    Output

    true

    impl Eq for Version {} is empty: Eq is a promise, not code. Comparing 1.2.0 < 1.10.0 compares numbers field by field, so it’s true, where comparing the text "1.2.0" < "1.10.0" would say false.

    Three more details:

    • Derives on generic types add bounds. #[derive(Clone)] struct Pair<T> { a: T, b: T } implements Clone for Pair<T> only when T: Clone. Generics, bounds & where covers bounds.
    • Free traits come from blanket implementations. The standard library has impl<T: Display> ToString for T and impl<T, U: From<T>> Into<U> for T. Implement Display or From, and those apply to your type automatically.
    • A derive costs nothing at run time. JSON.stringify and console.log walk an object’s properties while the program runs.C# records generate their members at compile time too, all of them at once, while serializers such as System.Text.Json use reflection at run time unless you opt into source generation. A derive produces plain functions that the compiler checks and optimizes like the ones you write.

    Common pitfalls

    Common pitfallDeref is not inheritance

    Deref makes a wrapper’s method calls fall through to the value inside, so it’s tempting to use it to “inherit” from another struct. It looks like it works:

    use std::ops::Deref;
    
    trait Describe {
        fn describe(&self) -> String;
    }
    
    struct Animal {
        name: String,
    }
    
    impl Describe for Animal {
        fn describe(&self) -> String {
            format!("{} the animal", self.name)
        }
    }
    
    struct Dog {
        animal: Animal,
    }
    
    impl Deref for Dog {
        type Target = Animal;
    
        fn deref(&self) -> &Animal {
            &self.animal
        }
    }
    
    fn introduce(subject: &impl Describe) {
        println!("{}", subject.describe());
    }
    
    fn main() {
        let dog = Dog {
            animal: Animal {
                name: String::from("Rex"),
            },
        };
        println!("{}", dog.describe()); // compiles: the call falls through to Animal
        introduce(&dog); // doesn't: Dog doesn't implement Describe
    }

    Rust doesn't compile this: error E0277

    error[E0277]: the trait bound `Dog: Describe` is not satisfied
      --> main.rs:40:15
       |
    40 |     introduce(&dog); // doesn't: Dog doesn't implement Describe
       |     --------- ^^^^ unsatisfied trait bound
       |     |
       |     required by a bound introduced by this call
       |
    help: the trait `Describe` is not implemented for `Dog`
      --> main.rs:17:1
       |
    17 | struct Dog {
       | ^^^^^^^^^^
       = help: the trait `Describe` is implemented for `Animal`
    note: required by a bound in `introduce`
      --> main.rs:29:29
       |
    29 | fn introduce(subject: &impl Describe) {
       |                             ^^^^^^^^ required by this bound in `introduce`

    But a Dog isn’t an Animal. It doesn’t implement Animal’s traits, so generic code rejects it, and if Dog defines its own describe, code holding the Animal still calls Animal’s: there’s no virtual dispatch here, only a fallback for method lookup. Share behavior with a trait that both types implement, and give Dog an animal field it uses explicitly.

    Common pitfallA float field blocks Eq, Hash and Ord

    #[derive(PartialEq, Eq)] on a struct with an f64 field fails with E0277, because f64 doesn’t implement Eq. Derive only PartialEq and PartialOrd. If the type must be a map key, store the value in a type that does implement Eq and Hash, such as whole cents in a u64 instead of dollars in an f64.

    Common pitfallDerived ordering follows field order

    A derived Ord compares fields from top to bottom. Move patch above major in the struct, and versions sort by patch number first, with no compiler error. For an enum, variants compare in declaration order. If the order matters, write a comment next to the fields, or implement Ord by hand.

    Common pitfallEqual values must have equal hashes

    If you write PartialEq by hand, say to compare names ignoring case, write Hash by hand to match. A derived Hash would hash “Ada” and “ADA” differently although they’re equal, and a HashSet would keep both. Clippy rejects that combination (derived_hash_with_manual_eq). It’s the same rule as overriding Equals without GetHashCode in C#, which the compiler warns about.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. Money should support +, print as dollars and cents, and be comparable, so you can find the cheapest price.

    Starting code in TypeScript
    money.ts
    class Money {
      cents: number;
      constructor(cents: number) {
        this.cents = cents;
      }
      plus(other: Money): Money {
        return new Money(this.cents + other.cents);
      }
      toString(): string {
        const rest = String(this.cents % 100).padStart(2, "0");
        return `$${Math.floor(this.cents / 100)}.${rest}`;
      }
    }
    
    const prices = [new Money(250), new Money(199), new Money(1000)];
    const total = prices.reduce((sum, price) => sum.plus(price), new Money(0));
    console.log(`total: ${total}`);
    const cheapest = prices.toSorted((a, b) => a.cents - b.cents)[0];
    console.log(`cheapest: ${cheapest}`);
    Starting code in C#
    Money.cs
    List<Money> prices = [new(250), new(199), new(1000)];
    var total = prices.Aggregate(new Money(0), (sum, price) => sum + price);
    Console.WriteLine($"total: {total}");
    Console.WriteLine($"cheapest: {prices.Min()}");
    
    readonly record struct Money(int Cents) : IComparable<Money>
    {
        public static Money operator +(Money a, Money b) => new(a.Cents + b.Cents);
        public int CompareTo(Money other) => Cents.CompareTo(other.Cents);
        public override string ToString() => $"${Cents / 100}.{Cents % 100:D2}";
    }

    Expected output

    total: $14.49
    cheapest: $1.99
    Show a hint

    Derive Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord and Default on a Money struct with a cents: u32 field. Implement Add so + works, and Display to print dollars and cents with write! and {:02}. With Ord derived, prices.iter().min() finds the cheapest.

    Show a solution
    use std::fmt;
    use std::ops::Add;
    
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
    struct Money {
        cents: u32,
    }
    
    impl Add for Money {
        type Output = Money;
    
        fn add(self, other: Money) -> Money {
            Money {
                cents: self.cents + other.cents,
            }
        }
    }
    
    impl fmt::Display for Money {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "${}.{:02}", self.cents / 100, self.cents % 100)
        }
    }
    
    fn main() {
        let prices = [
            Money { cents: 250 },
            Money { cents: 199 },
            Money { cents: 1000 },
        ];
        let total = prices
            .iter()
            .fold(Money::default(), |sum, &price| sum + price);
        println!("total: {total}");
        if let Some(cheapest) = prices.iter().min() {
            println!("cheapest: {cheapest}");
        }
    }

    The derives give Money equality, ordering and a zero default, so min() and fold(Money::default(), ...) work without hand-written code. Add supplies the + operator and Display the $14.49 text; println! with {} then uses Display directly, and .to_string() would work too.

    Saved in this browser only.