Hi !
I first used Generics back in the old C# days. Itβs a super cool feature. Letβs ask ChatGPT for a definition:
Generics in programming are a way to create classes and methods that work with multiple data types. They allow the programmer to define type parameters, which can be passed as arguments to methods, classes, and interfaces. This allows for the creation of reusable and efficient code, as a single implementation can work with different types. Generics help to eliminate the need for separate implementations for each data type.
ChatGPT: Describe generics in programming language in 4 lines.
Rust support generics, so we can define placeholders for structs, enums, methods and more.
A cool way to understand the use of Generics, is to work with a HashMap collection. A Hashmap has 2 generic types, one for the key and the 2nd one for the values.
We can create a HashMap collection to store names and ages, using a string datatype and an integer datatype.
let mut names_and_ages: HashMap<&str, i32> = HashMap::new();
names_and_ages.insert("Jeff the Squirrel", 2);
names_and_ages.insert("Ace the Puppy", 1);
names_and_ages.insert("Net the Cat", 4);
We can access the collection later and use it to print the values, with this output.
And this is the complete source code for this sample.
Super cool !
Happy coding!
Greetings
El Bruno
More posts in my blog ElBruno.com.
Top comments (0)