CodeBlanks Logo Icon CodeBlanks

Generic function

Write generic functions with <T>.

Generic functions

Generics let the same code work with different types. The type parameter is declared in angle brackets, and trait bounds say what can be done with it:

fn en_buyuk<T: PartialOrd + Copy>(v: &[T]) -> T {
    let mut eb = v[0];
    for &x in v {
        if x > eb {
            eb = x;
        }
    }
    eb
}

Without PartialOrd, > can't be used; without Copy, v[0] can't be copied out of the slice.

Monomorphization

The compiler generates the generic function separately for each concrete type it's used with. The calls en_buyuk(&[1, 2]) and en_buyuk(&['a', 'b']) produce two separate pieces of machine code:

// what the compiler produces (conceptually)
fn en_buyuk_i32(v: &[i32]) -> i32 { .. }
fn en_buyuk_char(v: &[char]) -> char { .. }

That's why generics have no runtime cost; the price is slightly longer compile times and a larger binary.

Practice Find the largest

Write the function en_buyuk<T: PartialOrd + Copy> above. Print the results for [3, 9, 2], ['a', 'z', 'm'] and [1.5, 2.5, 0.5] on one line separated by spaces.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn en_buyuk<T: PartialOrd + Copy>(v: &[T]) -> T {
    let mut eb = v[0];
    for &x in v {
        if x > eb {
            eb = x;
        }
    }
    eb
}

fn main() {
    println!("{} {} {}", en_buyuk(&[3, 9, 2]), en_buyuk(&['a', 'z', 'm']), en_buyuk(&[1.5, 2.5, 0.5]));
}

Expected output

9 z 2.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why doesn't <code>fn f&lt;T&gt;(a: T, b: T) -&gt; T { a + b }</code> compile?

  • It compiles
  • Addition isn't known to be defined for T; T: std::ops::Add<Output = T> is needed Correct answer
  • A generic function can't return a value
  • Two parameters can't share a type

Explanation: Every operation in generic code must be backed by a trait bound; the compiler assumes nothing else about T.

2 Type parameter

Question
fn en_buyuk____(v: &[T]) -> T {
    // ...
}
Answer
fn en_buyuk<T: PartialOrd + Copy>(v: &[T]) -> T {
    // ...
}

Explanation: T needs the PartialOrd and Copy bounds for comparing and copying.

3 Call and T

Term Meaning
en_buyuk(&[3, 9, 2]) i32
en_buyuk(&['a', 'z']) char
en_buyuk(&[1.5, 2.5]) f64
en_buyuk(&[1u8, 7]) u8

All lessons in Intermediate