8.9 Generics in Functions
Generics allow you to write flexible and reusable code by parameterizing types.
8.9.1 Max Function Variants
Variant 1: Using i32
Parameters
fn max_i32(a: i32, b: i32) -> i32 { if a > b { a } else { b } } fn main() { let result = max_i32(5, 10); println!("The maximum is {}", result); }
- A simple function that works only with
i32
types.
Variant 2: Using References
fn max_ref<'a>(a: &'a i32, b: &'a i32) -> &'a i32 { if a > b { a } else { b } } fn main() { let x = 5; let y = 10; let result = max_ref(&x, &y); println!("The maximum is {}", result); }
- This function accepts references to
i32
and returns a reference to the maximum value.
Variant 3: Using Generics
use std::cmp::PartialOrd; fn max_generic<T: PartialOrd>(a: T, b: T) -> T { if a > b { a } else { b } } fn main() { let int_max = max_generic(5, 10); let float_max = max_generic(5.5, 2.3); println!("The maximum integer is {}", int_max); println!("The maximum float is {}", float_max); }
- The
max_generic
function works with any type that implements thePartialOrd
trait (i.e., can be compared).
Generics will be explored in more detail in a later chapter.