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 class | Interface | |
| Has fields | Yes | Usually no |
| Has method bodies | Yes (some) | No (or default impls only) |
| Multiple "inheritance" | Usually no | Yes — 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
interfacekeyword; atraitis the interface, and a type opts in withimpl Trait for Type. - C# / Java — first-class
interfacekeyword. C# uses:for both inheritance and implementation; Java usesextendsfor inheritance andimplementsfor 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:
WoofFree plan: 30 tutor messages. PRO is unlimited.
