DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at on

#Rust πŸ¦€ – Working with Generics and Types πŸ‘

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);

Enter fullscreen mode Exit fullscreen mode

We can access the collection later and use it to print the values, with this output.

output of the complete solution printing the full collection of name and ages

And this is the complete source code for this sample.

Super cool !

Happy coding!


El Bruno

More posts in my blog

Top comments (0)