Start learning free

LESSON 649 OF 679 · OBJECT-ORIENTED PROGRAMMING

Interfaces in Rust

Lesson

TL ; DR:

An interface is a pure contract — a list of methods that a type promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


// Rust uses traits as interfaces:
trait Speaker {
    fn speak(&self);
}
struct Dog;
impl Speaker for Dog {
    fn speak(&self) { println!("Woof"); }
}


Full lesson:

An interface defines what a type can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all go(). In Rust you'd put go() in a Movable trait and have each one implement it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesUsually no
Has method bodiesYes (some)No (or default impls only)
Multiple "inheritance"Usually noYes — a type can implement many interfaces
Models"is a""can do"

In class-based languages a class inherits from at most one parent class but can implement many interfaces. Rust has no classes or inheritance at all: a struct can implement as many traits as you like. That's why interfaces are the right tool for cross-cutting capabilities like Clone, Debug, Iterator, etc.

The language landscape

  • Rust — no interface keyword; a trait is the interface, and a type opts in with impl Trait for Type.
  • C# / Java — first-class interface keyword. C# uses : for both inheritance and implementation; Java uses extends for inheritance and implements for interfaces.
  • Python — no separate interface; abstract base classes (ABCs) with all-abstract methods serve the same role.
  • JavaScript — no interface keyword in plain JS (TypeScript has it). The convention is a stub class.
  • C++ — a class with only pure-virtual methods is an interface. Multiple inheritance lets a class implement several.

Your task

Declare a Speaker trait with a speak method, then create a Dog struct that implements it, with a speak() method that prints "Woof". In main_function, call it through a Box<dyn Speaker>.

Expected output:

Woof
STEP 1 OF 6
    Ctrl + Enter to check