Rust Abstractions · 18 min · free with an account

Traits

Lesson preview · about 30%

Traits define shared behaviour independently of a concrete type.

Core idea

Generic bound: compile time. dyn Trait: runtime, one indirection.

Start with the idea

A generic bound is resolved at compile time, so the call is direct and inlinable. dyn Trait defers the choice to runtime through a vtable, which costs an indirection but lets you store different concrete types together in one collection. A dyn value has no size the compiler can plan for, so it lives behind a pointer: Box<dyn Trait> is what goes into a Vec.

A trait names behavior that multiple types can provide. Shape::area describes what a caller may ask without assuming how a circle or rectangle stores its dimensions. A generic parameter S: Shape selects a concrete implementation at compile time; a &dyn Shape or Box<dyn Shape> selects through a trait object at runtime. Both use the same trait contract, but they solve different API problems.

Use generics when a function can operate on one concrete type per call and compile-time specialization is useful.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery