Rust Tutorials: Multiple Generic Types 🚀

beginner
8 min

Rust Tutorials: Multiple Generic Types 🚀

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Rust, exploring a powerful concept known as Multiple Generic Types. 🎯

Why Multiple Generic Types?

In Rust, generics provide a way to write reusable code by specifying the types that a function or a type can work with. Multiple generic types allow us to write even more flexible and reusable code. 💡

Let's dive in!


Understanding Multiple Generic Types 📝

Multiple generic types are defined using the angle brackets <> and separated by a comma ,. Here's a simple example:

rust
fn identity<T, U>(t: T, u: U) -> (T, U) { (t, u) }

In this example, we have two generic types, T and U. This function takes values of any types and returns them as a tuple. ✅


Working with Multiple Generic Types 💡

To use a function or a type that takes multiple generic types, you simply need to provide the types when you call the function or create an instance of the type.

rust
let t1: i32 = 10; let u1: String = String::from("Hello"); let result = identity(t1, u1); println!("{:?}", result); // Output: (10, "Hello")

Here, we've provided an i32 for T and a String for U when calling the identity function.


Real-World Example 🌐

Let's create a simple generic list that can contain any type.

rust
struct GenericList<T> { data: Vec<T>, } impl<T> GenericList<T> { fn new() -> Self { GenericList { data: Vec::new() } } fn push(&mut self, value: T) { self.data.push(value); } fn pop(&mut self) -> Option<T> { self.data.pop() } } let mut list = GenericList::new::<i32>(); list.push(1); list.push(2); list.push(3); println!("{:?}", list.data); // Output: vec![1, 2, 3]

In this example, we've created a generic list that can contain any type. We use the GenericList struct and its methods with the push and pop functions. ✅


Challenge: Implement a Generic Max Function 💡

Create a generic function called max_of_two that takes two values of any type and returns the maximum one.

rust
fn max_of_two<T: PartialOrd + Copy>(a: T, b: T) -> T { if a > b { a } else { b } } let a = max_of_two(10u8, 5u8); let b = max_of_two(3.14f64, 2.71f64); println!("Max of a and b is: {}, {} ", a, b);
Quick Quiz
Question 1 of 1

What is the output of the max_of_two function call?


That's it for today! You now have a solid understanding of Multiple Generic Types in Rust. As always, practice makes perfect, so keep coding and exploring! 🚀

Happy learning!

  • CodeYourCraft Team 🌟