Rust Abstractions · 16 min · free with an account

Generics

Lesson preview · about 30%

Generics reuse an algorithm while keeping concrete types.

Core idea

Monomorphisation makes generics free at runtime.

Start with the idea

Trait bounds state exactly the capabilities the generic body needs, and the compiler generates a specialised copy per concrete type. That means generics cost nothing at runtime — but a bound wider than necessary narrows who can call you.

Generics let one implementation describe several concrete types without erasing what those types are. In the largest example, T is a placeholder chosen by the caller. The function does not need to know how to print or clone T; it only compares references, so PartialOrd is the capability that matters. A bound is a promise to the compiler about which operations the body may use, and it is a constraint on every caller. Adding Clone because it seems convenient would exclude useful types for no reason.

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