0
0
Rustprogramming~30 mins

Why generics are needed in Rust - See It in Action

Choose your learning style9 modes available
Why generics are needed
📖 Scenario: Imagine you want to write a function that can work with different types of data, like numbers or text, without rewriting the same code for each type.
🎯 Goal: You will build a simple Rust program that shows how generics let you write one function to handle multiple data types safely and easily.
📋 What You'll Learn
Create a function that adds two numbers of type i32
Create a function that adds two numbers of type f64
Create a generic function that adds two values of any type that supports addition
Print the results of calling each function
💡 Why This Matters
🌍 Real World
Generics are used in real programs to write flexible and reusable code, like collections that hold any type of data.
💼 Career
Understanding generics is important for Rust developers to write efficient, safe, and maintainable software.
Progress0 / 4 steps
1
Create two functions for adding numbers
Write a function called add_i32 that takes two i32 numbers and returns their sum. Also write a function called add_f64 that takes two f64 numbers and returns their sum.
Rust
Hint

Define two separate functions with the exact names add_i32 and add_f64. Each should return the sum of its two parameters.

2
Create a generic function for addition
Write a generic function called add_generic that takes two parameters of the same type T and returns their sum. Use the trait bound T: std::ops::Add to allow addition.
Rust
Hint

Use fn add_generic<T: std::ops::Add<Output = T>>(a: T, b: T) -> T and return a + b.

3
Call all three functions with example values
Call add_i32 with 5 and 10, call add_f64 with 1.5 and 2.5, and call add_generic with 3 and 7. Store the results in variables sum_i32, sum_f64, and sum_generic respectively.
Rust
Hint

Use let to store the results of calling each function with the exact values given.

4
Print the results
Print the values of sum_i32, sum_f64, and sum_generic each on its own line using println!.
Rust
Hint

Use println!("{}", variable); to print each sum on its own line.