Menu

[Rust Guide] 10.2. Generics
📰
0

[Rust Guide] 10.2. Generics

DEV Community·SomeB1oody·about 1 month ago
#GDvWsiLt
Reading 0:00
15s threshold

If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series. 10.2.1 What Are Generics The main purpose of generics is to improve code reusability . They are suitable for handling repeated-code problems, and can also be seen as separating data from algorithms . Generics are abstract substitutes for concrete types or other attributes. In other words, generic code is not the final code you write; it is more like a template with some placeholders . The compiler replaces those placeholders with concrete types at compile time. Let’s look at an example: fn largest < T > ( list : & [ T ]) -> T { //...... } Enter fullscreen mode Exit fullscreen mode This function definition uses a generic type parameter . T is the so-called “placeholder.” When you write the code, T can represent any type, but during compilation the compiler replaces T with a concrete type based on the actual usage. This process is called monomorphization . T is the generic type parameter.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More