14
Generics
Generics are templates for building unique functions and type definitions. Not surprisingly, generics are called templates in some other languages. Generics are templates with placeholders to be resolved later. You can then build unique instances of functions and type definitions by replacing the placeholders with concrete types. In this manner, generics represent reusable code, even in ways the author may not have anticipated. That is the fun part of generics—being able to use them in the future in unplanned ways. Combined with traits, we have the two pillars of polymorphism in Rust.
Many of the types in the standard library, such as Result<T, E>
, Option<T>
, Vec<T>
, and HashMap<K,V>
, are generic. For this reason, generics have an ...
Get Programming with Rust now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.