Bird
Raised Fist0
Rustprogramming~20 mins

Why generics are needed in Rust - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using generics?
Consider this Rust function that uses generics to find the largest element in a slice. What will it print?
Rust
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    let result = largest(&numbers);
    println!("The largest number is {}", result);
}
AThe largest number is 100
BRuntime panic due to empty slice
CCompilation error due to missing trait bounds
DThe largest number is 65
Attempts:
2 left
💡 Hint
Think about how the function compares elements and what the largest value in the list is.
🧠 Conceptual
intermediate
1:30remaining
Why do we need generics in Rust?
Which of the following best explains why generics are needed in Rust?
ATo allow functions and types to work with multiple data types without duplicating code
BTo enforce that all variables must be of the same type throughout the program
CTo make the compiler ignore type checking for faster compilation
DTo restrict functions to only work with primitive types
Attempts:
2 left
💡 Hint
Think about code reuse and flexibility with types.
🔧 Debug
advanced
2:30remaining
What error does this Rust code produce?
This code tries to find the largest element but does not use generics properly. What error will the compiler show?
Rust
fn largest(list: &[i32]) -> i32 {
    let mut largest = list[0];
    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    let result = largest(&numbers);
    println!("The largest number is {}", result);

    let chars = vec!['a', 'z', 'm', 'q'];
    let result = largest(&chars);
    println!("The largest char is {}", result);
}
ARuntime error: index out of bounds
BCompilation error: mismatched types, expected i32 but found char
CCompilation error: missing lifetime specifier
DThe program runs and prints the largest number and char
Attempts:
2 left
💡 Hint
Look at the function parameter types and the arguments passed.
📝 Syntax
advanced
1:30remaining
Which option correctly defines a generic struct in Rust?
You want to define a struct that can hold a value of any type. Which option is correct?
Astruct Point<T> { x: T; y: T; }
Bstruct Point { x: T, y: T }
Cstruct Point<T> (x: T, y: T);
Dstruct Point<T> { x: T, y: T }
Attempts:
2 left
💡 Hint
Remember Rust struct syntax and how generics are declared.
🚀 Application
expert
2:00remaining
How many items are in the resulting vector after this generic function call?
Given this generic function that duplicates each element in a vector, how many elements will the result vector have?
Rust
fn duplicate_elements<T: Clone>(input: Vec<T>) -> Vec<T> {
    let mut result = Vec::new();
    for item in input {
        result.push(item.clone());
        result.push(item);
    }
    result
}

fn main() {
    let v = vec![1, 2, 3];
    let duplicated = duplicate_elements(v);
    println!("Length: {}", duplicated.len());
}
A9
B3
C6
D4
Attempts:
2 left
💡 Hint
Each element is added twice to the result vector.

Practice

(1/5)
1. Why do we use generics in Rust?
fn print_value<T>(value: T) {}
easy
A. To limit functions to only one type of data
B. To write functions that work with many types without repeating code
C. To make the code run faster by using specific types only
D. To avoid using variables inside functions

Solution

  1. Step 1: Understand the purpose of generics

    Generics allow writing one function that can accept many types instead of writing many functions for each type.
  2. Step 2: Analyze the example function

    The function print_value<T> uses a placeholder T to accept any type, showing flexibility.
  3. Final Answer:

    To write functions that work with many types without repeating code -> Option B
  4. Quick Check:

    Generics = flexible reusable code [OK]
Hint: Generics = one code fits many types [OK]
Common Mistakes:
  • Thinking generics make code faster
  • Believing generics restrict types
  • Confusing generics with variables
2. Which of the following is the correct syntax to define a generic function in Rust?
easy
A. fn example<T>(value T) {}
B. fn example(value: T) {}
C. fn example<T> value: T {}
D. fn example<T>(value: T) {}

Solution

  1. Step 1: Recall Rust generic function syntax

    Generic functions use angle brackets <T> after the function name to declare type parameters.
  2. Step 2: Check each option

    fn example<T>(value: T) {} correctly uses fn example<T>(value: T) {}. Others miss brackets or have wrong parameter syntax.
  3. Final Answer:

    fn example<T>(value: T) {} -> Option D
  4. Quick Check:

    Generic syntax = fn name<T>(param: T) [OK]
Hint: Generic syntax always uses <T> after function name [OK]
Common Mistakes:
  • Omitting angle brackets for generics
  • Missing colon between parameter and type
  • Placing type parameter incorrectly
3. What will be the output of this Rust code?
fn print_type(value: T) {
    println!("Value: {}", value);
}

fn main() {
    print_type(10);
    print_type("hello");
}
medium
A. Compilation error due to missing trait
B. Value: 10 Value: 10
C. Value: 10 Value: hello
D. Runtime error printing value

Solution

  1. Step 1: Understand trait bound usage

    The generic type T requires the Display trait to print values with {}.
  2. Step 2: Check calls with different types

    Calling print_type(10) prints "Value: 10" and print_type("hello") prints "Value: hello" because both implement Display.
  3. Final Answer:

    Value: 10 Value: hello -> Option C
  4. Quick Check:

    Generics with Display trait print all types correctly [OK]
Hint: Generics with Display print any printable type [OK]
Common Mistakes:
  • Assuming generic needs no trait bound
  • Expecting same output for different inputs
  • Confusing compile and runtime errors
4. Identify the error in this Rust code using generics:
fn add<T>(a: T, b: T) -> T {
    a + b
}

fn main() {
    println!("{}", add(5, 10));
}
medium
A. Missing trait bound for + operator on T
B. Wrong return type declared
C. Function parameters should be references
D. Cannot use println! with generic functions

Solution

  1. Step 1: Check operator usage on generic type

    The + operator requires the type T to implement the Add trait.
  2. Step 2: Identify missing trait bound

    The function lacks T: std::ops::Add<Output = T> bound, causing a compile error.
  3. Final Answer:

    Missing trait bound for + operator on T -> Option A
  4. Quick Check:

    Operators need trait bounds on generics [OK]
Hint: Add operator needs trait bound on generic type [OK]
Common Mistakes:
  • Ignoring trait bounds for operators
  • Assuming all types support + by default
  • Thinking references are always required
5. You want to write a generic function that returns the largest of two values. Which is the correct way to define it in Rust?
hard
A. fn largest(a: T, b: T) -> T { if a > b { a } else { b } }
B. fn largest<T>(a: T, b: T) -> T { if a > b { a } else { b } }
C. fn largest(a: T, b: T) -> T { if a > b { a } else { b } }
D. fn largest(a: T, b: T) -> T { if a > b { a } else { b } }

Solution

  1. Step 1: Identify required trait for comparison

    To compare two values with >, the type T must implement PartialOrd.
  2. Step 2: Check trait bounds in options

    fn largest(a: T, b: T) -> T { if a > b { a } else { b } } correctly uses T: PartialOrd. fn largest<T>(a: T, b: T) -> T { if a > b { a } else { b } } misses trait bound, C uses Copy which is unrelated to comparison, D uses Display which is for printing.
  3. Final Answer:

    fn largest<T: PartialOrd>(a: T, b: T) -> T { if a > b { a } else { b } } -> Option A
  4. Quick Check:

    Comparison needs PartialOrd trait bound [OK]
Hint: Use PartialOrd trait to compare generics [OK]
Common Mistakes:
  • Omitting PartialOrd trait bound
  • Using unrelated traits like Copy or Display
  • Assuming all types can be compared
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard