Bird
Raised Fist0
Rustprogramming~20 mins

Generic functions in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Generic Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a generic function with different types

What is the output of this Rust program that uses a generic function to print values?

Rust
fn print_value<T: std::fmt::Display>(value: T) {
    println!("Value: {}", value);
}

fn main() {
    print_value(42);
    print_value("hello");
}
AValue: 42\nValue: \"hello\"
BValue: 42\nValue: hello
CValue: 42\nValue: hello\nValue: 42
DCompilation error due to missing trait bound
Attempts:
2 left
💡 Hint

Look at the trait bound std::fmt::Display and how it allows printing.

🧠 Conceptual
intermediate
1:30remaining
Understanding generic function constraints

Which statement best describes why generic functions in Rust often require trait bounds?

ATrait bounds specify what operations the generic type can perform, enabling the compiler to check correctness.
BTrait bounds allow generic functions to accept any type without restrictions.
CTrait bounds are optional and only used for documentation purposes.
DTrait bounds automatically convert types to a common type inside the function.
Attempts:
2 left
💡 Hint

Think about how Rust ensures safety and correctness with generics.

🔧 Debug
advanced
2:00remaining
Identify the error in this generic function

What error does this Rust code produce?

Rust
fn add<T>(a: T, b: T) -> T {
    a + b
}

fn main() {
    let result = add(5, 10);
    println!("{}", result);
}
Aerror: mismatched types between a and b
Berror: missing lifetime specifier
Cerror: binary operation `+` cannot be applied to type `T`
DNo error, prints 15
Attempts:
2 left
💡 Hint

Consider what trait is needed to use the + operator in Rust.

📝 Syntax
advanced
1:30remaining
Correct syntax for a generic function with multiple type parameters

Which option shows the correct syntax for a generic function that takes two different types and returns a tuple of them?

Afn pair<T, U>(a: T, b: U) -> (T, U) { (a, b) }
Bfn pair<T, U>(a: T, b: U) -> (U, T) { (a, b) }
Cfn pair<T, U>(a: T, b: U) -> (T, U) { a, b }
Dfn pair<T, U>(a: T, b: U) -> (T, U) { return a, b; }
Attempts:
2 left
💡 Hint

Remember how to return a tuple in Rust.

🚀 Application
expert
2:30remaining
Using generic functions with trait bounds and lifetimes

What is the output of this Rust program?

Rust
fn longest<'a, T>(x: &'a T, y: &'a T) -> &'a T
where
    T: std::fmt::Display + PartialOrd,
{
    if x >= y {
        println!("{} is longer or equal", x);
        x
    } else {
        println!("{} is longer", y);
        y
    }
}

fn main() {
    let a = "apple";
    let b = "banana";
    let result = longest(&a, &b);
    println!("Longest: {}", result);
}
Aapple is longer or equal\nLongest: apple
BRuntime panic due to lifetime mismatch
CCompilation error due to trait bound mismatch
Dbanana is longer\nLongest: banana
Attempts:
2 left
💡 Hint

Consider how string slices compare and the trait bounds used.

Practice

(1/5)
1. What does the <T> mean in a Rust function definition like fn example<T>(value: T) {}?
easy
A. It makes the function generic, so it can accept any type.
B. It defines a new variable inside the function.
C. It restricts the function to only work with integers.
D. It marks the function as unsafe.

Solution

  1. Step 1: Understand the syntax <T> in Rust

    The <T> after the function name declares a generic type parameter named T.
  2. Step 2: Explain the effect of generic type parameter

    This allows the function to accept any type for value, making it flexible and reusable.
  3. Final Answer:

    It makes the function generic, so it can accept any type. -> Option A
  4. Quick Check:

    Generic type parameter = flexible function input [OK]
Hint: Look for <T> after function name for generics [OK]
Common Mistakes:
  • Thinking <T> is a variable declaration
  • Assuming it restricts to one type like integer
  • Confusing it with unsafe code marker
2. Which of the following is the correct syntax to define a generic function named print_value that takes one argument of any type T?
easy
A. fn print_value(T value) {}
B. fn print_value<T>(value: T) {}
C. fn print_value(value: <T>) {}
D. fn print_value(value: T<>) {}

Solution

  1. Step 1: Recall generic function syntax in Rust

    Generic functions use <T> after the function name to declare the generic type.
  2. Step 2: Match the syntax with options

    fn print_value<T>(value: T) {} correctly places <T> after the function name and uses value: T as parameter type.
  3. Final Answer:

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

    Generic syntax = fn name<T>(param: T) [OK]
Hint: Generic type always goes after function name in angle brackets [OK]
Common Mistakes:
  • Putting T inside parameter parentheses incorrectly
  • Using angle brackets around parameter type
  • Missing angle brackets after function name
3. What will be the output of this Rust code?
fn show_value<T: std::fmt::Display>(val: T) {
    println!("Value: {}", val);
}

fn main() {
    show_value(10);
    show_value("hello");
}
medium
A. Value: 10\nValue: hello
B. Value: 10\nValue: 10
C. Compilation error due to missing trait bound
D. Runtime error

Solution

  1. Step 1: Understand the generic function with trait bound

    The function show_value requires T to implement Display so it can be printed.
  2. Step 2: Check calls with integer and string

    Both 10 (integer) and "hello" (string) implement Display, so both calls print correctly.
  3. Final Answer:

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

    Trait bound allows printing = output shown [OK]
Hint: Check trait bounds to know if printing works [OK]
Common Mistakes:
  • Assuming generic functions print without trait bounds
  • Thinking string prints as number
  • Expecting compilation error without trait bound
4. Identify the error in this generic function and how to fix it:
fn compare<T>(a: T, b: T) -> bool {
    a == b
}
medium
A. Function should return i32 instead of bool.
B. Function parameters should be references, not values.
C. Generic type T must be replaced with i32.
D. Missing trait bound T: PartialEq to use == operator.

Solution

  1. Step 1: Understand use of == in generic function

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

    The function lacks T: PartialEq bound, so compiler will error when using ==.
  3. Final Answer:

    Missing trait bound T: PartialEq to use == operator. -> Option D
  4. Quick Check:

    Operator needs trait bound = add T: PartialEq [OK]
Hint: Add trait bounds when using operators on generics [OK]
Common Mistakes:
  • Ignoring trait bounds for operators
  • Changing return type unnecessarily
  • Replacing generic with concrete type without reason
5. You want to write a generic function largest that returns the largest element from a slice of any type T. Which of these is the correct way to define it?
hard
A. fn largest<T>(list: &[T]) -> T { let mut largest = list[0]; for &item in list { if item > largest { largest = item; } } largest }
B. fn largest(list: &[i32]) -> i32 { let mut largest = list[0]; for &item in list { if item > largest { largest = item; } } largest }
C. fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = *list[0]; for &item in list { if item > largest { largest = item; } } largest }
D. fn largest<T: PartialEq>(list: &[T]) -> T { list[0] }

Solution

  1. Step 1: Identify required traits for comparison and copying

    To compare elements with >, T must implement PartialOrd. To copy elements, Copy trait is needed.
  2. Step 2: Check function signature and body

    fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = *list[0]; for &item in list { if item > largest { largest = item; } } largest } correctly adds T: PartialOrd + Copy and uses a loop to find the largest element.
  3. Final Answer:

    fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { ... } -> Option C
  4. Quick Check:

    Traits PartialOrd + Copy needed for generic largest function [OK]
Hint: Add PartialOrd and Copy traits for generic comparisons [OK]
Common Mistakes:
  • Omitting trait bounds causing compile errors
  • Returning wrong type or missing copy trait
  • Using concrete types instead of generics
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