Module 9 · Traits & generics
9.3impl Trait vs. dyn Trait
Static dispatch with generics and impl Trait, dynamic dispatch with &dyn Trait and Box<dyn Trait>, what a vtable and a fat pointer are, and how to choose between them and an enum.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Calling a method on "anything with this ability" | The method is looked up on the object when the call runs | A virtual call, found through the object's type at run time | Generics and impl Trait: picked at compile time. dyn Trait: through a vtable at run time |
| A parameter that accepts any implementing type | shape: Shape, an interface type | IShape shape, or T shape with where T : IShape | shape: &impl Shape (static) or shape: &dyn Shape (dynamic) |
| A list of different types with one ability | Shape[] | List<IShape> | Vec<Box<dyn Shape>> |
| A reference to a value through its interface | One pointer to the object | One pointer to the object; a struct is boxed first | &dyn Shape: two pointers, one to the data and one to the vtable |
| Boxing | Not a concept; every object is already reached through a reference | Implicit. A struct stored as an interface is copied into a new heap object | Never implicit. Box<dyn Shape> is a heap allocation you asked for with Box::new |
| Returning "some type with this ability" | Return the interface type | Return the interface type | -> impl Shape for one concrete type, -> Box<dyn Shape> when it varies |
In TypeScript, shape.area() finds area on the object when that line runs, whatever the object turns out to be.In C#, shape.Area() on an IShape is a virtual call: the runtime finds the right method through the object’s type when that line runs. Rust gives you two ways to call a trait method, and you pick one in the type you write. With static dispatch (generics and impl Trait), the compiler knows the concrete type and calls its method directly. With dynamic dispatch (&dyn Trait, Box<dyn Trait>), the pointer to the value comes with a second pointer, to a table of its type’s methods, and the call goes through that table. This lesson shows both, clears up what Box<dyn Trait> is (it isn’t implicit boxing), and ends with how to choose between them and an enum.
It builds on Traits and Generics, bounds & where.
Two ways to call a trait method
Here’s a Shape trait with two implementations, and two functions that describe any shape. The first is generic; the second takes the shape through the trait itself.
interface Shape {
name(): string;
area(): number;
}
class Square implements Shape {
side: number;
constructor(side: number) {
this.side = side;
}
name(): string {
return "square";
}
area(): number {
return this.side * this.side;
}
}
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;
}
}
// Types are erased: both functions run the same lookup at run time
function describeStatic<T extends Shape>(shape: T): string {
return `${shape.name()}: area ${shape.area()}`;
}
function describeDynamic(shape: Shape): string {
return `${shape.name()}: area ${shape.area()}`;
}
const square = new Square(2);
const rect = new Rectangle(3, 4);
console.log(describeStatic(square));
console.log(describeStatic(rect));
console.log(describeDynamic(square));
console.log(describeDynamic(rect));var square = new Square(2);
var rect = new Rectangle(3, 4);
Console.WriteLine(DescribeStatic(square));
Console.WriteLine(DescribeStatic(rect));
Console.WriteLine(DescribeDynamic(square)); // boxes square: it's a struct
Console.WriteLine(DescribeDynamic(rect));
// Generic: the JIT compiles a separate copy for each struct type, with no boxing
static string DescribeStatic<T>(T shape) where T : IShape => $"{shape.Name()}: area {shape.Area()}";
// Interface parameter: one copy, and every call is virtual
static string DescribeDynamic(IShape shape) => $"{shape.Name()}: area {shape.Area()}";
interface IShape
{
string Name();
double Area();
}
readonly record struct Square(double Side) : IShape
{
public string Name() => "square";
public double Area() => Side * Side;
}
readonly record struct Rectangle(double Width, double Height) : IShape
{
public string Name() => "rectangle";
public double Area() => Width * Height;
}trait Shape {
fn name(&self) -> &str;
fn area(&self) -> f64;
}
struct Square {
side: f64,
}
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Square {
fn name(&self) -> &str {
"square"
}
fn area(&self) -> f64 {
self.side * self.side
}
}
impl Shape for Rectangle {
fn name(&self) -> &str {
"rectangle"
}
fn area(&self) -> f64 {
self.width * self.height
}
}
// Static dispatch: the compiler writes one copy per shape type
fn describe_static(shape: &impl Shape) -> String {
format!("{}: area {}", shape.name(), shape.area())
}
// Dynamic dispatch: one copy; calls go through the vtable
fn describe_dynamic(shape: &dyn Shape) -> String {
format!("{}: area {}", shape.name(), shape.area())
}
fn main() {
let square = Square { side: 2.0 };
let rect = Rectangle {
width: 3.0,
height: 4.0,
};
println!("{}", describe_static(&square));
println!("{}", describe_static(&rect));
println!("{}", describe_dynamic(&square));
println!("{}", describe_dynamic(&rect));
}Output
square: area 4 rectangle: area 12 square: area 4 rectangle: area 12
The output is identical, and so is each function body. The difference is what the compiler builds:
describe_static(shape: &impl Shape)is a generic function. The compiler builds a separate copy for each type it’s called with, one forSquareand one forRectangle, and in each copyshape.area()is a direct call to that type’sarea. The optimizer can inline it. This is called monomorphization, and Generics, bounds & where covers it.describe_dynamic(shape: &dyn Shape)exists once.&dyn Shapemeans “a reference to some value that implementsShape; which type is only known at run time”. The reference carries a second pointer, to a vtable: a table with one entry per trait method.shape.area()looks up theareaentry and calls it.
In TypeScript, the two functions compile to the same JavaScript, because types are erased. Every call looks area up on the object (engines cache that lookup to make it fast). Rust lets you choose, and the two choices produce different machine code.
C# makes a similar split, but less visibly. Called with a struct, DescribeStatic<T> gets its own JIT-compiled copy, the calls are direct and square isn’t boxed. Called with classes, all reference types share one copy that makes interface calls. DescribeDynamic(IShape) boxes the Square before every call. Rust’s impl Shape always gets its own copy per type, and &dyn Shape never boxes anything.
Mental model shiftdyn marks the run-time choice
In Rust you can see in the type which kind of call you get. impl Shape or T: Shape: resolved at compile time. dyn Shape: resolved at run time through a vtable. Older code wrote &Shape or Box<Shape> without dyn; since the 2021 edition, dyn is required.
Lists of different types: Box<dyn Trait>
A generic function handles one type per copy, so it can’t help with a list that mixes squares and rectangles. A Vec stores its elements side by side, so every element must have the same size, and a Square (8 bytes) and a Rectangle (16 bytes) don’t. Vec<dyn Shape> doesn’t compile for that reason.
The fix is to store a pointer per element: every pointer has the same size, wherever it points. Box<dyn Shape> is an owned pointer to a shape on the heap, plus its vtable pointer. (The Shape, Square and Rectangle definitions are the same as above, so they’re hidden here and in the next example.)
// Each element is a reference to an object
const shapes: Shape[] = [new Square(2), new Rectangle(3, 4)];
for (const shape of shapes) {
console.log(`${shape.name()}: area ${shape.area()}`);
}
const total = shapes.reduce((sum, shape) => sum + shape.area(), 0);
console.log(`total: ${total}`);// Each struct is boxed: copied into its own heap object
List<IShape> shapes = [new Square(2), new Rectangle(3, 4)];
foreach (var shape in shapes)
{
Console.WriteLine($"{shape.Name()}: area {shape.Area()}");
}
var total = shapes.Sum(shape => shape.Area());
Console.WriteLine($"total: {total}");fn main() {
// Each element: a pointer to a heap allocation, plus a vtable pointer
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Square { side: 2.0 }),
Box::new(Rectangle {
width: 3.0,
height: 4.0,
}),
];
for shape in &shapes {
println!("{}: area {}", shape.name(), shape.area());
}
let total: f64 = shapes.iter().map(|shape| shape.area()).sum();
println!("total: {total}");
}Output
square: area 4 rectangle: area 12 total: 16
Box::new(Square { side: 2.0 }) makes a Box<Square>. Because the vector’s type says Box<dyn Shape>, Rust converts it on the spot: the pointer stays the same, and the compiler adds a pointer to Square’s vtable next to it. Nothing is copied or allocated a second time. Method calls look through the box, so shape.area() works on each element without a *.
Box<dyn Trait> is not boxing
Other languages use the word “boxing” for something the runtime does on its own: quietly copying a plain value into a heap object so it can be treated like any other object. You never manage that in TypeScript, and Rust’s Box isn’t that idea. It’s a heap allocation you ask for explicitly with Box::new. A Box<dyn Shape> is two pointers: one to that allocation, which holds a single shape’s fields and nothing else, and one to that type’s vtable.
The name invites a mix-up with C# boxing, so here it is directly. In C#, IShape shape = square; with a struct boxes: the runtime allocates a new heap object, copies the struct into it behind the header and method-table pointer every heap object has, and shape refers to that copy. You didn’t write new, and changing square afterwards doesn’t change the box. (A class instance assigned to IShape isn’t boxed: it’s already a heap object, so only the reference is copied.)
A Rust Box<dyn Shape> is a heap allocation you asked for with Box::new. The value moves in, so there’s no stale original. The allocation holds only the shape’s fields, with no type header; the vtable pointer lives in the Box itself, next to the data pointer. And dyn doesn’t need a box at all: &dyn Shape points at a value wherever it is, on the stack included, and allocates nothing.
C# interface variable holding a struct | Rust Box<dyn Shape> | Rust &dyn Shape | |
|---|---|---|---|
| Heap allocation | Yes, implicit | Yes, you wrote Box::new | No |
| The value | Copied into the box | Moved into the box | Borrowed where it is |
| Where the type information lives | A method-table pointer at the start of the heap object | A vtable pointer next to the data pointer | A vtable pointer next to the data pointer |
| Size of the variable | One pointer | Two pointers | Two pointers |
So Box doesn’t make something dynamic; dyn does. Box is just one way to own a dyn value. If the shapes are owned somewhere else, Vec<&dyn Shape> holds borrowed trait objects with no allocations: let shapes: Vec<&dyn Shape> = vec![&square, &rect];.
Or use an enum
If you know every kind of shape up front, an enum holds them all in one type, with no Box and no vtable:
enum Shape {
Square { side: f64 },
Rectangle { width: f64, height: f64 },
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Square { side } => side * side,
Shape::Rectangle { width, height } => width * height,
}
}
}
fn main() {
let shapes = [
Shape::Square { side: 2.0 },
Shape::Rectangle {
width: 3.0,
height: 4.0,
},
];
let total: f64 = shapes.iter().map(Shape::area).sum();
println!("total: {total}");
}Output
total: 16
The trade-off runs in opposite directions. With an enum, adding a new kind means editing the enum and every match, and the compiler lists each match you missed; adding a new operation is one new method. With dyn Trait, anyone can add a new kind (another module, another crate) by implementing the trait, but adding an operation means changing the trait and every implementation. Enums with data covers the enum side.
impl Trait in argument and return position
impl Trait means different things depending on where you write it.
In a parameter, shape: &impl Shape is shorthand for a generic parameter: fn describe<T: Shape>(shape: &T). The caller picks the type, and every type gets its own copy of the function.
In a return type, -> impl Trait means “this function returns one concrete type that implements the trait, and I’m not telling you which”. The function picks the type, and it must be the same type on every path. Callers can only use what the trait offers, but calls are still static.
That rule decides the factory below. In TypeScriptC#, makeShape returns the interface type, so it can return a square on one path and a rectangle on another. In Rust, two different types means Box<dyn Shape>:
function makeShape(kind: string, size: number): Shape {
if (kind === "square") {
return new Square(size);
}
return new Rectangle(size, size * 2);
}
for (const kind of ["square", "rectangle"]) {
const shape = makeShape(kind, 3);
console.log(`${shape.name()}: area ${shape.area()}`);
}foreach (var kind in new[] { "square", "rectangle" })
{
var shape = MakeShape(kind, 3);
Console.WriteLine($"{shape.Name()}: area {shape.Area()}");
}
static IShape MakeShape(string kind, double size) =>
kind == "square" ? new Square(size) : new Rectangle(size, size * 2);fn make_shape(kind: &str, size: f64) -> Box<dyn Shape> {
if kind == "square" {
Box::new(Square { side: size })
} else {
Box::new(Rectangle {
width: size,
height: size * 2.0,
})
}
}
fn main() {
for kind in ["square", "rectangle"] {
let shape = make_shape(kind, 3.0);
println!("{}: area {}", shape.name(), shape.area());
}
}Output
square: area 9 rectangle: area 18
With -> impl Shape instead, the two branches have different types, and the compiler rejects it:
fn make_shape(kind: &str, size: f64) -> impl Shape {
if kind == "square" {
Square { side: size }
} else {
Rectangle {
width: size,
height: size * 2.0,
}
}
}Rust doesn't compile this: error E0308
error[E0308]: `if` and `else` have incompatible types
--> main.rs:5:9
|
2 | / if kind == "square" {
3 | | Square { side: size }
| | --------------------- expected because of this
4 | | } else {
5 | |/ Rectangle {
6 | || width: size,
7 | || height: size * 2.0,
8 | || }
| ||_________^ expected `Square`, found `Rectangle`
9 | | }
| |______- `if` and `else` have incompatible types
|
help: you could change the return type to be a boxed trait object
|
1 - fn make_shape(kind: &str, size: f64) -> impl Shape {
1 + fn make_shape(kind: &str, size: f64) -> Box<dyn Shape> {
|
help: if you change the return type to expect trait objects, box the returned expressions
|
3 ~ Box::new(Square { side: size })
4 | } else {
5 ~ Box::new(Rectangle {
6 | width: size,
7 | height: size * 2.0,
8 ~ })
|-> impl Trait shines when the concrete type exists but is long or impossible to write. Closures and iterator chains have such types. This function returns a Map<RangeInclusive<u32>, {closure}>, which you can’t name, so it says what callers need to know:
fn squares(limit: u32) -> impl Iterator<Item = u32> {
(1..=limit).map(|n| n * n)
}
fn main() {
let list: Vec<String> = squares(4).map(|n| n.to_string()).collect();
println!("{}", list.join(" "));
}Output
1 4 9 16
Lazy iterators and Closures use this a lot.
Not every trait can be dyn
A vtable holds one function pointer per method, fixed when the program is compiled. Some methods can’t fit that shape, and a trait with such a method can’t be used as dyn Trait. The rules are called dyn compatibility (older docs and error messages call it “object safety”). The two you’ll meet most:
- A generic method, like
fn scale<T: Into<f64>>(&self, factor: T). The compiler would need one copy perT, and it can’t know in advance which ones to put in the vtable. - A method that returns
Selfby value, likefn scaled(&self, factor: f64) -> Self. Through adyn Shape, the caller doesn’t know the concrete type, so it doesn’t know how many bytes the result takes.
A function without self, such as a constructor fn new() -> Self, has the same problem in another form: there’s no value whose vtable could be used to find it.
TypeScript has no such rule, because any interface can type a variable: methods are looked up by name when they’re called.C# interfaces can have generic methods, because the runtime compiles each instantiation when it’s first called. Rust compiles everything ahead of time, so a vtable can only hold a fixed list of functions. Here’s a trait that adds a scaled method, and a list that needs dyn:
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self;
}
struct Square {
side: f64,
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
fn scaled(&self, factor: f64) -> Self {
Square {
side: self.side * factor,
}
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 2.0 })];
println!("{}", shapes.len());
}Rust doesn't compile this: error E0038
error[E0038]: the trait `Shape` is not dyn compatible
--> main.rs:22:29
|
22 | let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 2.0 })];
| ^^^^^ `Shape` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> main.rs:3:38
|
1 | trait Shape {
| ----- this trait is not dyn compatible...
2 | fn area(&self) -> f64;
3 | fn scaled(&self, factor: f64) -> Self;
| ^^^^ ...because method `scaled` references the `Self` type in its return type
= help: consider moving `scaled` to another trait
= help: only type `Square` implements `Shape`; consider using it directly instead.You have two fixes. If the method doesn’t need to work through dyn, add where Self: Sized to it. That opts this one method out of the vtable: the trait becomes dyn compatible again, and you can still call scaled on a concrete Square. If it does need to work through dyn, return a trait object instead: fn scaled(&self, factor: f64) -> Box<dyn Shape>.
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self
where
Self: Sized;
}
struct Square {
side: f64,
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
fn scaled(&self, factor: f64) -> Self {
Square {
side: self.side * factor,
}
}
}
fn main() {
let big = Square { side: 2.0 }.scaled(3.0); // fine on a concrete type
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(big)];
println!("{}", shapes[0].area());
}Output
36
Standard traits follow the same rules. Clone returns Self (and so requires Self: Sized, which the error message mentions), so Box<dyn Clone> isn’t allowed; Display and Debug only take &self, so &dyn Display and Box<dyn std::error::Error> are common.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
&impl Trait or <T: Trait> (parameter) | A function works with any type that has the ability, one type per call. The default. | Static dispatch: direct calls the optimizer can inline, and no allocation. | fn describe(shape: &impl Shape); call describe(&square). Use <T: Trait> when two parameters must share a type. |
-> impl Trait | The function always returns the same concrete type, and you can’t or don’t want to name it: closures, iterator chains. | Callers get static calls, and your concrete type stays private. | fn squares(limit: u32) -> impl Iterator<Item = u32>. |
&dyn Trait | You borrow values whose type is only known at run time, or you want one compiled copy of a large function. | No allocation; one copy of the code; each call goes through the vtable. | fn describe(shape: &dyn Shape); &square converts automatically. Vec<&dyn Shape> for borrowed lists. |
Box<dyn Trait> | You own values of different types in one list, field or return value. | Each value gets its own heap allocation, so values of different sizes fit behind same-size pointers. | Vec<Box<dyn Shape>>, shapes.push(Box::new(square)), -> Box<dyn Shape>. |
enum | You know every kind up front and they all live in your crate. | One type, no allocation and no vtable; match is exhaustive, so a new variant shows every place to update. | enum Shape { Square { side: f64 }, Rectangle { .. } } with a match per method. |
Rule of thumb: start with generics or impl Trait. If values of different types must mix at run time, use an enum when you know every type, and dyn Trait when the set is open: &dyn Trait to borrow, Box<dyn Trait> to own. Box is never what makes something dynamic; dyn is.
Does each call, variable or return value hold just one concrete type (even if different calls use different types)?
YesNoUse generics or
impl TraitStatic dispatch: one compiled copy per type, direct calls, no allocation.Do you know every type up front, and do they all live in your crate?
YesNoUse an
enumNoBoxand no vtable. The compiler checks everymatchwhen you add a variant.Do you only need to borrow the values for a while?
YesNoUse
&dyn TraitPoints at values wherever they already are; nothing is allocated.Otherwise: Use
Box<dyn Trait>: each value gets its own heap allocation, and the list, field or return value owns it.
Under the hood
Here’s what each kind of pointer costs:
println!("&Square: {} bytes", size_of::<&Square>());
println!("Box<Square>: {} bytes", size_of::<Box<Square>>());
println!("&dyn Shape: {} bytes", size_of::<&dyn Shape>());
println!("Box<dyn Shape>: {} bytes", size_of::<Box<dyn Shape>>());Output
&Square: 8 bytes Box<Square>: 8 bytes &dyn Shape: 16 bytes Box<dyn Shape>: 16 bytes
A reference or Box to a known type is one pointer. A reference or Box to a dyn type is two pointers, a fat pointer: one to the data and one to the vtable. On a 64-bit target that’s 16 bytes instead of 8, and a Vec<Box<dyn Shape>> stores 16 bytes per element in its buffer.
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
&Square | data ptr8 bytes · pointer | 8 bytes | |||||||||||||||
Box<Square> | data ptr8 bytes · pointer | 8 bytes | |||||||||||||||
&dyn Shape | data ptr8 bytes · pointer | vtable ptr8 bytes · pointer | 16 bytes | ||||||||||||||
Box<dyn Shape> | data ptr8 bytes · pointer | vtable ptr8 bytes · pointer | 16 bytes | ||||||||||||||
Each row is drawn to scale in bytes, on a 64-bit target. A &Square and a Box<Square> are each one 8-byte pointer to the square's data. A &dyn Shape and a Box<dyn Shape> are each 16 bytes: an 8-byte pointer to the data and an 8-byte pointer to the vtable for the value's concrete type.
Here’s a borrowed trait object and an owned one in memory:
let square = Square { side: 2.0 };
let by_ref: &dyn Shape = □
let boxed: Box<dyn Shape> = Box::new(Rectangle {
width: 3.0,
height: 4.0,
});
println!("{} {}", by_ref.area(), boxed.area());Output
4 12
What the picture shows:
by_refallocates nothing. Its data pointer leads tosquareon the stack.dynis about how calls are made, not where the data lives.boxedowns one heap allocation holding the rectangle’s two numbers and nothing else: no header, no type tag. Whenboxedgoes out of scope, Rust runs the vtable’sdropentry (none here: twof64s need no cleanup, but a type holding aStringwould have one) and frees the allocation, using the size and alignment stored there.- Vtables belong to types, not values. The compiler builds
Rectangle’s vtable forShapeahead of time, in the program’s read-only data, and every&dyn ShapeorBox<dyn Shape>holding aRectanglepoints to that shared table. No value gets its own, though the compiler may keep a few identical copies. Today it holds the drop entry, size and alignment, then the trait’s methods; Rust doesn’t promise that layout. boxed.area()loads theareaentry from the vtable and calls it with the data pointer asself.
&dyn Shape without changing it, and why the same Square costs nothing extra when you use it directly.&dyn Shape where it is, and a Square used directly carries no header.The performance trade-off. Static dispatch makes a copy of each generic function per type. Calls are direct and can be inlined, which lets the optimizer simplify across them, but many types times large functions means a bigger binary and longer compile times. Dynamic dispatch keeps one copy, and each call is an indirect jump through the vtable that usually can’t be inlined. Box<dyn Trait> adds a heap allocation per value, and each element of a list is a separate allocation to follow. For most code the difference doesn’t matter; it matters in tight loops over many values, so measure before trading clarity for it.
Common pitfalls
Common pitfallBoxing every argument out of habit
A function that only reads a shape doesn’t need to own it. fn print_area(shape: Box<dyn Shape>) forces every caller to allocate a box and give the shape away. Take shape: &dyn Shape, or shape: &impl Shape for static dispatch. Both accept &square, and a caller who already has a Box<dyn Shape> can pass &boxed to the &dyn Shape version. Keep Box<dyn Trait> for the places that own values of mixed types: collections, struct fields and return values.
Common pitfallA dyn Trait forgets the concrete type
In TypeScript you can recover a type from an interface value with instanceof or a kind tag.In C# you can recover a type from an interface value with is Square square or a switch on type. A &dyn Shape offers only the trait’s methods; there’s no built-in check for “is this a Square?”. If you need to branch on the concrete type, that’s the sign you want an enum and a match. (std::any::Any can downcast, but it’s meant for rare plumbing code, not everyday design.)
Common pitfallAdding a method can break every dyn user
A trait that’s used as dyn Shape stays usable only while every method is dyn compatible. Adding a generic method or a method returning Self to it breaks every dyn Shape in the program with E0038, even code that never calls the new method. Add where Self: Sized to that method, as shown above, and the trait keeps working as dyn.
Common pitfall-> impl Trait is one type, not any type
-> impl Shape doesn’t mean “returns some shape, maybe a different one each time”. It means one hidden concrete type, and returning a Square on one path and a Rectangle on another fails with E0308. Return Box<dyn Shape>, or an enum, when the type depends on run-time input.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. It sends one message through a list of notifiers of different types.
interface Notifier {
send(message: string): string;
}
class Email implements Notifier {
address: string;
constructor(address: string) {
this.address = address;
}
send(message: string): string {
return `email to ${this.address}: ${message}`;
}
}
class Sms implements Notifier {
phone: string;
constructor(phone: string) {
this.phone = phone;
}
send(message: string): string {
return `sms to ${this.phone}: ${message}`;
}
}
function notifyAll(notifiers: Notifier[], message: string): void {
for (const notifier of notifiers) {
console.log(notifier.send(message));
}
}
const notifiers: Notifier[] = [new Email("ada@example.com"), new Sms("555-0100")];
notifyAll(notifiers, "build passed");List<INotifier> notifiers = [new Email("ada@example.com"), new Sms("555-0100")];
NotifyAll(notifiers, "build passed");
static void NotifyAll(List<INotifier> notifiers, string message)
{
foreach (var notifier in notifiers)
{
Console.WriteLine(notifier.Send(message));
}
}
interface INotifier
{
string Send(string message);
}
record Email(string Address) : INotifier
{
public string Send(string message) => $"email to {Address}: {message}";
}
record Sms(string Phone) : INotifier
{
public string Send(string message) => $"sms to {Phone}: {message}";
}Expected output
email to ada@example.com: build passed sms to 555-0100: build passed
Show a hint
Make Notifier a trait with fn send(&self, message: &str) -> String, and implement it for Email and Sms structs. The list mixes two types and owns them, so its element type is Box<dyn Notifier>. notify_all only reads the list, so it can take &[Box<dyn Notifier>].
Show a solution
trait Notifier {
fn send(&self, message: &str) -> String;
}
struct Email {
address: String,
}
struct Sms {
phone: String,
}
impl Notifier for Email {
fn send(&self, message: &str) -> String {
format!("email to {}: {message}", self.address)
}
}
impl Notifier for Sms {
fn send(&self, message: &str) -> String {
format!("sms to {}: {message}", self.phone)
}
}
fn notify_all(notifiers: &[Box<dyn Notifier>], message: &str) {
for notifier in notifiers {
println!("{}", notifier.send(message));
}
}
fn main() {
let notifiers: Vec<Box<dyn Notifier>> = vec![
Box::new(Email {
address: String::from("ada@example.com"),
}),
Box::new(Sms {
phone: String::from("555-0100"),
}),
];
notify_all(¬ifiers, "build passed");
}The list holds an Email and an Sms, which are different types with different sizes, so each one goes in its own Box and the vector stores fat pointers: data plus vtable. notify_all borrows the list as a slice, and each notifier.send call goes through that value's vtable. An enum would also work here if these two were the only kinds you ever needed.
Saved in this browser only.