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.1Traits

    How Rust traits declare shared behavior, why every type opts in with an explicit impl, how default methods and associated functions work, and which traits you may implement for which types.

    About 25 minutesIntermediate

    On this page
    1. Concept map
    2. A trait is a contract a type signs up to
    3. Matching methods are not enough
    4. Default methods
    5. Traits for types you didn’t write
    6. Standard traits for your types
    7. The orphan rule
    8. Associated functions and Self
    9. Traits replace inheritance
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    A named set of methods several types shareinterfaceinterfacetrait
    How a type signs upNothing to write: any value with matching members fits. implements is an optional checkclass Square : IShapeimpl Shape for Square, a block of its own
    A method with a body in the contractNot in an interface; use an abstract base classA default interface method, callable only through the interface typeA default method, callable on the type directly
    Adding a method to a type you didn't writeA plain function (patching a built-in prototype works, but changes it for everyone)An extension methodImplement your trait for it: impl Shout for str
    Static members in the contractNot allowed in an interfacestatic abstract members, with the TSelf pattern to name your own typeAssociated functions, such as fn unit() -> Self
    Sharing code between typesClass inheritance with extendsClass inheritance with : BaseDefault methods for behavior, a field of another struct for data

    A TypeScriptC# interface lists the methods a type must have. A Rust trait does the same job, with three differences that change how you design code. A type only implements a trait when you write impl Trait for Type, even if its methods already match. A trait can carry code, both default methods and functions with no self. And you can implement your own trait for types you didn’t write, str and Vec included, under one rule about who may implement what. Traits are also how Rust shares behavior without inheritance.

    A trait is a contract a type signs up to

    Here’s a Shape with two methods, two types that implement it, and a function that describes any shape.

    TypeScript
    shapes.ts
    interface Shape {
      name(): string;
      area(): number;
    }
    
    class Rectangle implements Shape {
      width: number;
      height: number;
    
      constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
      }
    
      name(): string {
        return "rectangle";
      }
    
      area(): number {
        return this.width * this.height;
      }
    }
    
    class Square implements Shape {
      side: number;
    
      constructor(side: number) {
        this.side = side;
      }
    
      name(): string {
        return "square";
      }
    
      area(): number {
        return this.side * this.side;
      }
    }
    
    function describe(shape: Shape): string {
      return `${shape.name()} with area ${shape.area()}`;
    }
    
    const rect = new Rectangle(3, 4);
    const square = new Square(2);
    console.log(describe(rect));
    console.log(describe(square));
    C#
    Shapes.cs
    var rect = new Rectangle(3, 4);
    var square = new Square(2);
    Console.WriteLine(Describe(rect));
    Console.WriteLine(Describe(square));
    
    static string Describe(IShape shape) => $"{shape.Name()} with area {shape.Area()}";
    
    interface IShape
    {
        string Name();
        int Area();
    }
    
    class Rectangle(int width, int height) : IShape
    {
        public string Name() => "rectangle";
        public int Area() => width * height;
    }
    
    class Square(int side) : IShape
    {
        public string Name() => "square";
        public int Area() => side * side;
    }
    Rust
    trait Shape {
        fn name(&self) -> &str;
        fn area(&self) -> u32;
    }
    
    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    struct Square {
        side: u32,
    }
    
    impl Shape for Rectangle {
        fn name(&self) -> &str {
            "rectangle"
        }
    
        fn area(&self) -> u32 {
            self.width * self.height
        }
    }
    
    impl Shape for Square {
        fn name(&self) -> &str {
            "square"
        }
    
        fn area(&self) -> u32 {
            self.side * self.side
        }
    }
    
    fn describe(shape: &impl Shape) -> String {
        format!("{} with area {}", shape.name(), shape.area())
    }
    
    fn main() {
        let rect = Rectangle {
            width: 3,
            height: 4,
        };
        let square = Square { side: 2 };
        println!("{}", describe(&rect));
        println!("{}", describe(&square));
    }

    Output

    rectangle with area 12
    square with area 4
    • trait Shape lists method signatures, ending in ; instead of a body. It plays the role of the interfaceinterface.
    • impl Shape for Rectangle is where Rectangle signs the contract. The methods go in this block, not in the struct and not in impl Rectangle. A type can implement any number of traits, each in its own block.
    • describe(shape: &impl Shape) takes a borrow of any type that implements Shape. The next lesson shows that this is shorthand for a generic function.
    • Trait methods have no pub: if the trait is visible, so are all its methods.

    Mental model shifttrait, impl and impl Trait are three different things

    trait Shape { … } declares a contract. impl Shape for Square { … } fulfills it for one type. impl Square { … }, with no trait, adds methods that belong to Square alone (its inherent methods, from Structs & impl blocks). And impl Shape in a parameter’s type means “some type that implements Shape”.

    Matching methods are not enough

    TypeScript interfaces are structural: any value with the right members fits, and implements is only a check you can ask for. This object literal never mentions Shape, and describe accepts it:

    blob.ts
    const blob = { name: () => "blob", area: () => 7 };
    console.log(describe(blob));

    Output

    blob with area 7

    Rust traits are nominal: the type must say impl Shape for Blob. Matching method names prove nothing.

    Rust traits are nominal, like C# interfaces: a class with a Name() and an Area() method isn’t an IShape until it says : IShape, and a Rust type isn’t a Shape until there’s an impl Shape for it.

    Blob has a name and an area method with exactly the right signatures, but they’re its own inherent methods, so it isn’t a Shape:

    struct Blob;
    
    impl Blob {
        fn name(&self) -> &str {
            "blob"
        }
    
        fn area(&self) -> u32 {
            7
        }
    }
    
    fn main() {
        println!("{}", describe(&Blob));
    }

    Rust doesn't compile this: error E0277

    error[E0277]: the trait bound `Blob: Shape` is not satisfied
      --> blob.rs:14:29
       |
    14 |     println!("{}", describe(&Blob));
       |                    -------- ^^^^^ unsatisfied trait bound
       |                    |
       |                    required by a bound introduced by this call
       |
    help: the trait `Shape` is not implemented for `Blob`
      --> blob.rs:1:1
       |
     1 | struct Blob;
       | ^^^^^^^^^^^
    help: this trait has no implementations, consider adding one
      --> blob.rs
       |
       | trait Shape {
       | ^^^^^^^^^^^
    note: required by a bound in `describe`
      --> blob.rs
       |
       | fn describe(shape: &impl Shape) -> String {
       |                          ^^^^^ required by this bound in `describe`

    The fix is to move both methods into an impl Shape for Blob block. Being explicit has a payoff: a method called area on some unrelated type can’t make it a Shape by accident, and the compiler can tell you exactly which trait a type is missing.

    Default methods

    A trait method can have a body. Every implementing type gets it for free, and any type can replace it with its own version. Here describe moves into the trait, and Square overrides it:

    TypeScript
    shapes.ts
    abstract class Shape {
      abstract name(): string;
      abstract area(): number;
    
      describe(): string {
        return `${this.name()} with area ${this.area()}`;
      }
    }
    
    class Rectangle extends Shape {
      width: number;
      height: number;
    
      constructor(width: number, height: number) {
        super();
        this.width = width;
        this.height = height;
      }
    
      name(): string {
        return "rectangle";
      }
    
      area(): number {
        return this.width * this.height;
      }
    }
    
    class Square extends Shape {
      side: number;
    
      constructor(side: number) {
        super();
        this.side = side;
      }
    
      name(): string {
        return "square";
      }
    
      area(): number {
        return this.side * this.side;
      }
    
      override describe(): string {
        return `square with side ${this.side}`;
      }
    }
    
    const rect = new Rectangle(3, 4);
    const square = new Square(2);
    console.log(rect.describe());
    console.log(square.describe());
    C#
    Shapes.cs
    IShape rect = new Rectangle(3, 4);
    IShape square = new Square(2);
    Console.WriteLine(rect.Describe());
    Console.WriteLine(square.Describe());
    
    interface IShape
    {
        string Name();
        int Area();
    
        string Describe() => $"{Name()} with area {Area()}";
    }
    
    class Rectangle(int width, int height) : IShape
    {
        public string Name() => "rectangle";
        public int Area() => width * height;
    }
    
    class Square(int side) : IShape
    {
        public string Name() => "square";
        public int Area() => side * side;
        public string Describe() => $"square with side {side}";
    }
    Rust
    trait Shape {
        fn name(&self) -> &str;
        fn area(&self) -> u32;
    
        fn describe(&self) -> String {
            format!("{} with area {}", self.name(), self.area())
        }
    }
    
    impl Shape for Rectangle {
        fn name(&self) -> &str {
            "rectangle"
        }
    
        fn area(&self) -> u32 {
            self.width * self.height
        }
    }
    
    impl Shape for Square {
        fn name(&self) -> &str {
            "square"
        }
    
        fn area(&self) -> u32 {
            self.side * self.side
        }
    
        fn describe(&self) -> String {
            format!("square with side {}", self.side)
        }
    }
    
    fn main() {
        let rect = Rectangle {
            width: 3,
            height: 4,
        };
        let square = Square { side: 2 };
        println!("{}", rect.describe());
        println!("{}", square.describe());
    }

    Output

    rectangle with area 12
    square with side 2

    TypeScript interfaces can’t hold code, so the nearest match is an abstract class. That costs you the one base class a TypeScript class may extend. A Rust type can implement any number of traits, each with its own default methods.C# default interface methods have a catch: they’re only reachable through the interface type. With var rect = new Rectangle(3, 4), the call rect.Describe() is error CS1061, which is why the C# version declares IShape rect. In Rust, rect.describe() works on the Rectangle itself. The default body can call the trait’s other methods through self, as describe calls self.name() and self.area(). It can’t touch fields, because a trait doesn’t know what fields its types have.

    Traits for types you didn’t write

    You can implement your own trait for any type, including str, i32 and Vec<T> from the standard library. The methods then work on those values with ordinary dot syntax:

    TypeScript
    shout.ts
    function shout(text: string): string {
      return `${text.toUpperCase()}!`;
    }
    
    const name = "ada";
    console.log(shout("hello"));
    console.log(shout(name));
    C#
    Shout.cs
    var name = "ada";
    Console.WriteLine("hello".Shout());
    Console.WriteLine(name.Shout());
    
    static class TextExtensions
    {
        public static string Shout(this string text) => $"{text.ToUpper()}!";
    }
    Rust
    trait Shout {
        fn shout(&self) -> String;
    }
    
    impl Shout for str {
        fn shout(&self) -> String {
            format!("{}!", self.to_uppercase())
        }
    }
    
    fn main() {
        let name = String::from("ada");
        println!("{}", "hello".shout());
        println!("{}", name.shout());
    }

    Output

    HELLO!
    ADA!

    TypeScript can’t add a method to string without patching String.prototype, which changes every string in the program, including the ones other libraries use. A Rust impl is scoped: .shout() only works where the Shout trait is in scope, and the str type itself is untouched.This looks like a C# extension method, and it’s used the same way. The difference is that a Rust impl really implements the trait: str is now a Shout, so any function that requires a Shout accepts a string. An extension method can’t make string implement an interface. name.shout() works on a String too, because method calls look through a String to the str inside it.

    Standard traits for your types

    The other direction is just as common: implementing a standard library trait for your own type. Display is the trait behind {} in println! and format!, the job toString()ToString() does in TypeScriptC#:

    TypeScript
    rectangle.ts
    class Rectangle {
      width: number;
      height: number;
    
      constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
      }
    
      toString(): string {
        return `${this.width}x${this.height}`;
      }
    }
    
    const rect = new Rectangle(3, 4);
    console.log(`Rectangle: ${rect}`);
    const label = rect.toString();
    console.log(`${label.length} characters`);
    C#
    Rectangle.cs
    var rect = new Rectangle(3, 4);
    Console.WriteLine($"Rectangle: {rect}");
    var label = rect.ToString();
    Console.WriteLine($"{label.Length} characters");
    
    class Rectangle(int width, int height)
    {
        public override string ToString() => $"{width}x{height}";
    }
    Rust
    use std::fmt;
    
    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    impl fmt::Display for Rectangle {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{}x{}", self.width, self.height)
        }
    }
    
    fn main() {
        let rect = Rectangle {
            width: 3,
            height: 4,
        };
        println!("Rectangle: {rect}");
        let label = rect.to_string();
        println!("{} characters", label.len());
    }

    Output

    Rectangle: 3x4
    3 characters

    You implement one method, fmt, and get both {rect} and rect.to_string(): the standard library gives to_string to every type that implements Display. Standard traits covers Display and its relatives in depth.

    The orphan rule

    There’s one limit. Roughly, you may write impl Trait for Type only if the trait or the type is defined in your crate (your package). (The full rule has extra cases for generic traits: impl From<YourType> for Vec<u8> is allowed because your type appears in the trait. This version covers everyday code.) Shout for str is fine: Shout is yours. Display for Rectangle is fine: Rectangle is yours. Display for Vec<String> is not, because both come from the standard library:

    use std::fmt;
    
    impl fmt::Display for Vec<String> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{}", self.join(", "))
        }
    }
    
    fn main() {
        let names = vec![String::from("Ada"), String::from("Grace")];
        println!("{names}");
    }

    Rust doesn't compile this: error E0117

    error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
     --> names.rs:3:1
      |
    3 | impl fmt::Display for Vec<String> {
      | ^^^^^^^^^^^^^^^^^^^^^^-----------
      |                       |
      |                       `Vec` is not defined in the current crate
      |
      = note: impl doesn't have any local type before any uncovered type parameters
      = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
      = note: define and implement a trait or new type instead

    This is called the orphan rule: an impl must live next to its trait or next to its type, never apart from both. It exists so that there is at most one implementation of a trait for a type in a whole program, a property called coherence. If two libraries could each implement Display for Vec<String>, a program that used both would have two answers to “how does this print?” and no way to choose. A TypeScript program in the same spot, with two libraries patching the same method onto a prototype, silently keeps whichever ran last.C# meets the same problem with extension methods: two libraries can each define Shout(this string), and a file that imports both namespaces gets an ambiguous-call error (CS0121) at the call.

    The standard way around it is a newtype: wrap the foreign type in a one-field struct of your own. The struct is yours, so the impl is allowed, and the wrapper costs nothing at run time:

    use std::fmt;
    
    struct Names(Vec<String>);
    
    impl fmt::Display for Names {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{}", self.0.join(", "))
        }
    }
    
    fn main() {
        let names = Names(vec![String::from("Ada"), String::from("Grace")]);
        println!("{names}");
    }

    Output

    Ada, Grace

    Associated functions and Self

    A trait can also require functions with no self at all, like a static method. Inside a trait, Self means “whichever type is implementing this”, so a trait can say “returns a value of your own type” once, for every implementation:

    TypeScript
    shapes.ts
    interface Shape {
      scaled(factor: number): Shape;
      area(): number;
    }
    
    class Square implements Shape {
      side: number;
    
      constructor(side: number) {
        this.side = side;
      }
    
      static unit(): Square {
        return new Square(1);
      }
    
      scaled(factor: number): Square {
        return new Square(this.side * factor);
      }
    
      area(): number {
        return this.side * this.side;
      }
    }
    
    const square = Square.unit().scaled(3);
    console.log(`square side ${square.side}, area ${square.area()}`);
    C#
    Shapes.cs
    var square = Square.Unit().Scaled(3);
    Console.WriteLine($"square side {square.Side}, area {square.Area()}");
    
    interface IShape<TSelf> where TSelf : IShape<TSelf>
    {
        static abstract TSelf Unit();
        TSelf Scaled(int factor);
        int Area();
    }
    
    class Square(int side) : IShape<Square>
    {
        public int Side { get; } = side;
        public static Square Unit() => new(1);
        public Square Scaled(int factor) => new(Side * factor);
        public int Area() => Side * Side;
    }
    Rust
    trait Shape {
        fn unit() -> Self;
        fn scaled(&self, factor: u32) -> Self;
        fn area(&self) -> u32;
    }
    
    struct Square {
        side: u32,
    }
    
    impl Shape for Square {
        fn unit() -> Self {
            Self { side: 1 }
        }
    
        fn scaled(&self, factor: u32) -> Self {
            Self {
                side: self.side * factor,
            }
        }
    
        fn area(&self) -> u32 {
            self.side * self.side
        }
    }
    
    fn main() {
        let square = Square::unit().scaled(3);
        println!("square side {}, area {}", square.side, square.area());
    }

    Output

    square side 3, area 9
    • fn unit() -> Self has no self parameter, so it’s an associated function, called with :: as Square::unit(). Every implementing type must provide one.
    • -> Self in the trait becomes -> Square in Square’s impl, and would be -> Rectangle in an impl for Rectangle. That’s why square.side works after .scaled(3): the result is a Square, not just “some shape”.

    A TypeScript interface can’t require a static method. It can return the polymorphic this type, but that only fits methods that return the object itself, not a new one. So scaled returns Shape, Square narrows it to Square by hand, and nothing would complain if another shape class forgot unit.C# needs two features for this: static abstract members (C# 11) and the TSelf pattern, IShape<TSelf> where TSelf : IShape<TSelf>, because an interface has no built-in name for “the implementing type”. Rust has Self in every trait, and associated functions need no special keyword. Requiring unit in the trait pays off in generic code, which can call T::unit() for any shape type T. The next lesson shows how.

    Traits replace inheritance

    Rust has no class inheritance. Structs & impl blocks showed how fields are reused: put one struct inside another. Everything else a base class does maps onto traits:

    A base class gives youIn Rust
    Shared fieldsA field holding another struct (composition)
    Shared method codeDefault methods in a trait
    Overriding a methodImplementing the trait method instead of using the default
    “Is a” (pass a Square where a shape is expected)A trait bound or impl Trait (this module)
    An abstract methodA trait method with no body
    Interface inheritanceA supertrait: trait Solid: Shape

    A supertrait says “to implement this trait, a type must also implement that one”. The trait’s default methods can then call the other trait’s methods:

    trait Shape {
        fn area(&self) -> u32;
    }
    
    trait Solid: Shape {
        fn depth(&self) -> u32;
    
        fn volume(&self) -> u32 {
            self.area() * self.depth()
        }
    }
    
    struct Brick {
        width: u32,
        height: u32,
        depth: u32,
    }
    
    impl Shape for Brick {
        fn area(&self) -> u32 {
            self.width * self.height
        }
    }
    
    impl Solid for Brick {
        fn depth(&self) -> u32 {
            self.depth
        }
    }
    
    fn main() {
        let brick = Brick {
            width: 2,
            height: 3,
            depth: 4,
        };
        println!("volume {}", brick.volume());
    }

    Output

    volume 24

    trait Solid: Shape is interface Solid extends Shapeinterface ISolid : IShape, not a base class: Brick still implements each trait in its own block, and no fields are inherited. One thing inheritance has that traits don’t: an override can’t call the default it replaces (there’s no super.describe()). If an override needs the shared logic, put it in a plain function that both can call.

    Which one should I use?

    Coming from TypeScriptC#, the instinct is to start with an interfaceinterface. In Rust, most behavior starts as plain methods, and a trait comes in when a second type needs the same ability.

    WhatWhenWhyHow
    Inherent methodThe behavior belongs to one type and uses its fields. The default.Simplest: no trait to declare or import.impl Square { fn area(&self) -> u32 { … } }, called square.area().
    TraitSeveral types share an ability, code should accept any of them, and new types may join later, including ones in other crates.One contract, checked at compile time. Calls are direct, with no run-time lookup. It also works on types you didn’t write.trait Shape { fn area(&self) -> u32; }, then impl Shape for Square { … } per type.
    Default methodMost implementations would write the same body.Written once; types that need something else override it.Give the trait method a body: fn describe(&self) -> String { … }.
    Enum and matchA fixed list of kinds that you define in one place, like the shapes your app draws.Adding a method is one match, and the compiler checks every kind is handled. Values of different kinds fit in one Vec.enum Shape { Square(u32), Rectangle(u32, u32) }. See Enums with data.
    Free functionThe behavior doesn’t belong to any one type: it combines several, or is a helper.No type has to own it.fn total_area(a: &Square, b: &Rectangle) -> u32.
    Newtype and traitYou need a standard trait (or another crate’s) on a type you don’t own.The orphan rule forbids the direct impl; the wrapper is yours.struct Names(Vec<String>); then impl Display for Names.

    The same choice as questions; the first “yes” gives the answer:

    Where should this behavior go?
    1. Is it the same operation over a fixed list of kinds that you define in one place?

      Yes

      An enum with a method that uses matchThe compiler checks every kind is covered. Adding a new kind means updating every match.

      No
    2. Do several types (yours, the standard library's or another crate's) need it, and should some code accept any of them?

      Yes

      A trait, with an impl Trait for Type per typeGive shared bodies to default methods. For a foreign trait on a foreign type, wrap the type in a newtype first.

      No
    3. Does it belong to one type and use that type's fields?

      Yes

      An inherent method in impl TypeTurn it into a trait later, when a second type needs it.

      No
    4. Otherwise: A free function: fn total_area(a: &Square, b: &Rectangle) -> u32.

    Rule of thumb: start with inherent methods. Add a trait when a second type needs the same ability and some code has to accept either one. If the set of kinds is closed and yours, an enum is usually simpler than a trait.

    Under the hood

    A trait method is an ordinary function whose first argument is the receiver. The compiler knows the concrete type of rect, so rect.area() is a direct call to Rectangle’s area, and these three lines make the same call:

    let rect = Rectangle {
        width: 3,
        height: 4,
    };
    let a = rect.area();
    let b = Shape::area(&rect);
    let c = <Rectangle as Shape>::area(&rect); // "Rectangle's impl of Shape"
    assert_eq!((a, b, c), (12, 12, 12));
    assert_eq!(size_of::<Rectangle>(), 8); // still just two u32s
    • Implementing a trait adds nothing to the value. A Rectangle is still 8 bytes, its two u32 fields. There’s no object header and no pointer to a method table. A TypeScript interface disappears entirely when compiled; at run time, shape.area() looks the method up on the object and its prototype chain (engines cache the lookup).A C# object, by contrast, carries a header and a pointer to its type’s method table, and a call through IShape is dispatched at run time.
    • A default method is generic over the implementing type. Like the generic functions in the next lesson, describe gets its own compiled copy for each type that uses the default, so Rectangle’s copy calls Rectangle’s name and area directly. Nothing looks the type up at run time.
    • Run-time dispatch is opt-in. Rust only looks methods up at run time when you ask for a trait object, written dyn Shape. impl Trait vs. dyn Trait covers it.
    • Coherence is checked when you compile. Besides the orphan rule, two impls of one trait for one type in your own code are a compile error (E0119, shown in the next lesson), so which impl runs is never a run-time surprise.

    Common pitfalls

    Common pitfallThe trait must be in scope to call its methods

    Trait methods only work with dot syntax where the trait itself is imported. Here Square is imported but Shape isn’t, so square.area() isn’t found:

    mod shapes {
        pub trait Shape {
            fn area(&self) -> u32;
        }
    
        pub struct Square {
            pub side: u32,
        }
    
        impl Shape for Square {
            fn area(&self) -> u32 {
                self.side * self.side
            }
        }
    }
    
    use shapes::Square;
    
    fn main() {
        let square = Square { side: 2 };
        println!("{}", square.area());
    }

    Rust doesn't compile this: error E0599

    error[E0599]: no method named `area` found for struct `Square` in the current scope
      --> main.rs:21:27
       |
     3 |         fn area(&self) -> u32;
       |            ---- the method is available for `Square` here
    ...
     6 |     pub struct Square {
       |     ----------------- method `area` not found for this struct
    ...
    21 |     println!("{}", square.area());
       |                           ^^^^ method not found in `Square`
       |
       = help: items from traits can only be used if the trait is in scope
    help: trait `Shape` which provides `area` is implemented but not in scope; perhaps you want to import it
       |
     1 + use crate::shapes::Shape;
       |

    The compiler’s help names the trait. Fix it with use shapes::Shape; (or use shapes::{Shape, Square};). It’s the same rule as C# extension methods, which need their namespace’s using, except that in Rust it applies to every trait method.TypeScript has no equivalent, because a method is just a property of the object. The common standard traits, such as Clone and ToString, are imported for you by the prelude, so you rarely notice the rule until you write your own traits in a separate module. Modules & visibility covers use.

    Common pitfallEvery method without a default is required

    Leave out a required method and the impl doesn’t compile, even if no code calls that method yet:

    trait Shape {
        fn name(&self) -> &str;
        fn area(&self) -> u32;
    }
    
    struct Square {
        side: u32,
    }
    
    impl Shape for Square {
        fn area(&self) -> u32 {
            self.side * self.side
        }
    }

    Rust doesn't compile this: error E0046

    error[E0046]: not all trait items implemented, missing: `name`
      --> main.rs:10:1
       |
     2 |     fn name(&self) -> &str;
       |     ----------------------- `name` from trait
    ...
    10 | impl Shape for Square {
       | ^^^^^^^^^^^^^^^^^^^^^ missing `name` in implementation

    The error lists the missing methods. Add them, or give the method a default body in the trait if most types would write the same thing.

    Common pitfallTwo traits, one method name

    A type can implement two traits that both have a name method. Calling cat.name() is then ambiguous:

    trait Shape {
        fn name(&self) -> String;
    }
    
    trait Pet {
        fn name(&self) -> String;
    }
    
    struct Cat;
    
    impl Shape for Cat {
        fn name(&self) -> String {
            String::from("cat-shaped")
        }
    }
    
    impl Pet for Cat {
        fn name(&self) -> String {
            String::from("Tom")
        }
    }
    
    fn main() {
        println!("{}", Cat.name());
    }

    Rust doesn't compile this: error E0034

    error[E0034]: multiple applicable items in scope
      --> main.rs:24:24
       |
    24 |     println!("{}", Cat.name());
       |                        ^^^^ multiple `name` found
       |
    note: candidate #1 is defined in an impl of the trait `Pet` for the type `Cat`
      --> main.rs:18:5
       |
    18 |     fn name(&self) -> String {
       |     ^^^^^^^^^^^^^^^^^^^^^^^^
    note: candidate #2 is defined in an impl of the trait `Shape` for the type `Cat`
      --> main.rs:12:5
       |
    12 |     fn name(&self) -> String {
       |     ^^^^^^^^^^^^^^^^^^^^^^^^
    help: disambiguate the method for candidate #1
       |
    24 -     println!("{}", Cat.name());
    24 +     println!("{}", Pet::name(&Cat));
       |
    help: disambiguate the method for candidate #2
       |
    24 -     println!("{}", Cat.name());
    24 +     println!("{}", Shape::name(&Cat));
       |

    Say which one you mean with the trait’s name in front:

    let cat = Cat;
    println!("{}", Pet::name(&cat));
    println!("{}", <Cat as Shape>::name(&cat));

    Output

    Tom
    cat-shaped
    It’s the Rust form of C# explicit interface implementation, where you cast to IPet to pick one. In Rust you don’t cast: you name the trait at the call.
    TypeScript can’t have this clash: an object has only one property called name.

    Try it yourself

    Exercise: port this to Rust

    Port this to Rust with a Priced trait. Every item has a price in cents, and a label that defaults to that price in cents; a gift overrides the label. The other versions need a wrapper type for a plain tip amount. In Rust, implement the trait for u32 directly, so a tip is just a number.

    Starting code in TypeScript
    priced.ts
    abstract class Priced {
      abstract cents(): number;
    
      label(): string {
        return `${this.cents()} cents`;
      }
    }
    
    class Book extends Priced {
      price: number;
    
      constructor(price: number) {
        super();
        this.price = price;
      }
    
      cents(): number {
        return this.price;
      }
    }
    
    class Gift extends Priced {
      cents(): number {
        return 0;
      }
    
      override label(): string {
        return "free gift";
      }
    }
    
    class Tip extends Priced {
      amount: number;
    
      constructor(amount: number) {
        super();
        this.amount = amount;
      }
    
      cents(): number {
        return this.amount;
      }
    }
    
    console.log(new Book(1299).label());
    console.log(new Gift().label());
    console.log(new Tip(150).label());
    Starting code in C#
    Priced.cs
    IPriced book = new Book(1299);
    IPriced gift = new Gift();
    IPriced tip = new Tip(150);
    Console.WriteLine(book.Label());
    Console.WriteLine(gift.Label());
    Console.WriteLine(tip.Label());
    
    interface IPriced
    {
        int Cents();
        string Label() => $"{Cents()} cents";
    }
    
    class Book(int price) : IPriced
    {
        public int Cents() => price;
    }
    
    class Gift : IPriced
    {
        public int Cents() => 0;
        public string Label() => "free gift";
    }
    
    class Tip(int amount) : IPriced
    {
        public int Cents() => amount;
    }

    Expected output

    1299 cents
    free gift
    150 cents
    Show a hint

    Declare trait Priced with fn cents(&self) -> u32; and give fn label(&self) -> String a default body. Gift overrides label. For the tip, impl Priced for u32 and return *self.

    Show a solution
    trait Priced {
        fn cents(&self) -> u32;
    
        fn label(&self) -> String {
            format!("{} cents", self.cents())
        }
    }
    
    struct Book {
        price: u32,
    }
    
    impl Priced for Book {
        fn cents(&self) -> u32 {
            self.price
        }
    }
    
    struct Gift;
    
    impl Priced for Gift {
        fn cents(&self) -> u32 {
            0
        }
    
        fn label(&self) -> String {
            String::from("free gift")
        }
    }
    
    impl Priced for u32 {
        fn cents(&self) -> u32 {
            *self
        }
    }
    
    fn main() {
        let book = Book { price: 1299 };
        let tip: u32 = 150;
        println!("{}", book.label());
        println!("{}", Gift.label());
        println!("{}", tip.label());
    }

    label is a default method, so Book and the u32 impl get it without writing it, and Gift replaces it. Implementing Priced for u32 is allowed because Priced is your trait, so the tip needs no wrapper type: a plain u32 is now Priced, and tip.label() calls the default method on it.

    Saved in this browser only.