CodeBlanks Logo Icon CodeBlanks

Summary - Generics

Combine generic struct, method and enum to build Pair<T>.

Generics summary

Generics let you write type-independent code: functions (fn f<T>), structs (struct S<T>), enums (enum E<T>) and methods (impl<T> S<T>). Trait bounds say what can be done with T. A concrete-type impl S<f64> can be written. When the type can't be inferred, the turbofish ::<T> is used. Thanks to monomorphization there's no runtime cost.

A swap function

Some generics need no trait bound at all: a function that only moves values doesn't need to know anything about T:

fn takas<T>(c: (T, T)) -> (T, T) {
    (c.1, c.0)
}

println!("{:?}", takas((1, 2)));   // (2, 1)

But since printing with {:?} happens on the caller's side, T: Debug is needed there, not in the function itself.

Practice Swap

Write the function fn takas<T>(c: (T, T)) -> (T, T) above. Print the results of takas((1, 2)) and takas(("a", "b")) with {:?}, separated by a space.

Starter code

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

Sample solution

main.rs
fn takas<T>(c: (T, T)) -> (T, T) {
    (c.1, c.0)
}

fn main() {
    println!("{:?} {:?}", takas((1, 2)), takas(("a", "b")));
}

Expected output

(2, 1) ("b", "a")

Questions and answers

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

1 If a generic function is called with 3 different types, how many copies does the compiler produce?

  • 3 Correct answer
  • 1
  • It's decided at runtime
  • 0

Explanation: Monomorphization produces a separate, optimized version for each concrete type.

2 Unbounded generic

Question
fn takas____(c: (T, T)) -> (T, T) {
    (c.1, c.0)
}
Answer
fn takas<T>(c: (T, T)) -> (T, T) {
    (c.1, c.0)
}

Explanation: A function that only moves values needs no bound.

3 Group summary

Term Meaning
fn f<T>(x: T) Generic function
struct S<T> Generic struct
impl<T> S<T> Generic methods
::<T> Turbofish

All lessons in Intermediate