0
0
Rustprogramming~30 mins

Generic functions in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Generic Functions in Rust
📖 Scenario: You are building a small Rust program that can work with different types of data using a single function. This helps avoid repeating code for each data type.
🎯 Goal: Create a generic function in Rust that can take two values of the same type and return the larger one. You will practice writing generic functions and calling them with different types.
📋 What You'll Learn
Create a generic function named largest that takes two parameters of the same generic type T.
Add a trait bound to T so it can be compared using the greater than operator.
Call the largest function with two i32 values and print the result.
Call the largest function with two f64 values and print the result.
💡 Why This Matters
🌍 Real World
Generic functions let programmers write flexible code that works with many data types without repeating themselves.
💼 Career
Understanding generics is important for writing clean, reusable code in Rust and many other programming languages.
Progress0 / 4 steps
1
Create a generic function skeleton
Write a generic function named largest that takes two parameters a and b of the same generic type T. For now, just return a without any comparison.
Rust
Hint

Use fn largest(a: T, b: T) -> T to define a generic function.

2
Add trait bound for comparison
Modify the largest function to add a trait bound so that T can be compared using the greater than operator. Use PartialOrd and Copy traits. Then return the larger of a and b using an if expression.
Rust
Hint

Use T: PartialOrd + Copy to allow comparison and copying.

3
Call the generic function with integers
Call the largest function with two i32 values: 10 and 20. Store the result in a variable named result_int.
Rust
Hint

Call largest(10, 20) and assign to result_int.

4
Call the generic function with floats and print results
Call the largest function with two f64 values: 3.5 and 2.7. Store the result in a variable named result_float. Then print both result_int and result_float using println!.
Rust
Hint

Use println!("Largest integer: {}", result_int); and similarly for result_float.