Back to course

Introduction to Generic Types

Rust for Systems & Web3 Security

Write Code for Any Type

Generics allow you to write functions or structs that work with multiple types without duplicating code.

rust fn largest<T: PartialOrd>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest }

Generics are zero-cost abstractions; Rust generates specific code for each type used at compile time (Monomorphization).