20.8 Generics Instead of Traditional OOP
In many languages, you might reach for classes and inheritance to write functions or types that operate on multiple data types. Rust instead promotes generics for compile-time polymorphism. Rather than storing everything in a base class pointer, you write generic functions or structs that can handle multiple types under trait constraints.
Example: Generic Function
fn print_elements<T: std::fmt::Debug>(data: &[T]) { for element in data { println!("{:?}", element); } } fn main() { let nums = vec![1, 2, 3]; let words = vec!["hello", "world"]; print_elements(&nums); print_elements(&words); }
By using T: std::fmt::Debug
, we allow our function to handle any type that implements the Debug
trait, achieving reuse without an inheritance chain.