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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access