Ad space (banner)
Lesson 17 / 20

Generics

This lesson covers generics, which let you write one function that works with many types.

Generics use the <T> notation to declare a type variable whose actual type is decided later. The same logic can then be reused across different types.

The sample code defines fn largest<T: PartialOrd + Copy>(list: &[T]) -> T and finds the largest value in a slice of numbers. PartialOrd is the constraint (the trait bound) meaning "can be compared".

A common early stumble is specifying those trait bounds. Whatever you want to do with the generic type T — compare it, copy it — has to be stated explicitly as a constraint.

In professional work, much of the standard library, including Vec and Option, is implemented with generics.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)