Bird
Raised Fist0
Rustprogramming~10 mins

Generics with traits in Rust - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a generic function that prints any type implementing the Display trait.

Rust
use std::fmt::Display;

fn print_value<T: [1]>(value: T) {
    println!("{}", value);
}

fn main() {
    print_value(42);
    print_value("hello");
}
Drag options to blanks, or click blank then click option'
ADisplay
BCopy
CClone
DDebug
Attempts:
3 left
💡 Hint
Common Mistakes
Using Debug instead of Display causes a formatting error with {}.
Omitting the trait bound causes a compile error.
2fill in blank
medium

Complete the code to implement a trait bound for a generic function that returns the length of any type that implements the Len trait.

Rust
trait Len {
    fn len(&self) -> usize;
}

fn get_length<T: [1]>(item: T) -> usize {
    item.len()
}

struct MyString(String);

impl Len for MyString {
    fn len(&self) -> usize {
        self.0.len()
    }
}

fn main() {
    let s = MyString(String::from("hello"));
    println!("Length: {}", get_length(s));
}
Drag options to blanks, or click blank then click option'
ALen
BClone
CDisplay
DCopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated traits like Clone or Display causes errors.
Forgetting the trait bound causes a compile error.
3fill in blank
hard

Fix the error in the generic function by adding the correct trait bound to allow comparison.

Rust
fn largest<T: [1]>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    println!("Largest number is {}", largest(&numbers));
}
Drag options to blanks, or click blank then click option'
ADisplay
BPartialOrd
CCopy
DClone
Attempts:
3 left
💡 Hint
Common Mistakes
Using Copy or Clone does not provide comparison operators.
Omitting the trait bound causes a compile error.
4fill in blank
hard

Fill both blanks to define a generic struct with a trait bound and implement a method that uses the trait.

Rust
use std::fmt::[1];

struct Wrapper<T: [2]> {
    value: T,
}

impl<T: Display> Wrapper<T> {
    fn show(&self) {
        println!("Value: {}", self.value);
    }
}

fn main() {
    let w = Wrapper { value: 123 };
    w.show();
}
Drag options to blanks, or click blank then click option'
ADisplay
BDebug
DClone
Attempts:
3 left
💡 Hint
Common Mistakes
Using Debug instead of Display causes formatting errors.
Mismatching trait bounds between struct and impl causes errors.
5fill in blank
hard

Fill all three blanks to complete a generic function that returns the longer of two string slices using trait bounds.

Rust
fn longest<'a, T: [1] + [2]>(x: &'a T, y: &'a T) -> &'a T {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let s1 = String::from("hello");
    let s2 = String::from("world!");
    let result = longest(&s1, &s2);
    println!("Longest string is: {}", result);
}
Drag options to blanks, or click blank then click option'
ADisplay
BAsRef<str>
CPartialOrd
DDebug
Attempts:
3 left
💡 Hint
Common Mistakes
Using only Display without AsRef causes errors calling len().
Omitting trait bounds causes compile errors.

Practice

(1/5)
1. What is the main purpose of using generics with traits in Rust?
easy
A. To restrict functions to only work with primitive types
B. To allow functions or structs to work with different types that implement specific behavior
C. To enable dynamic typing in Rust
D. To automatically convert types without explicit code

Solution

  1. Step 1: Understand generics

    Generics allow writing code that works with multiple types without repeating code.
  2. Step 2: Understand traits with generics

    Traits define behavior. Using traits with generics means the generic type must implement certain behavior.
  3. Final Answer:

    To allow functions or structs to work with different types that implement specific behavior -> Option B
  4. Quick Check:

    Generics + traits = flexible code with behavior constraints [OK]
Hint: Generics + traits = flexible code with behavior constraints [OK]
Common Mistakes:
  • Thinking generics only work with primitive types
  • Confusing traits with dynamic typing
  • Assuming automatic type conversion
2. Which of the following is the correct syntax to declare a generic function in Rust that requires the generic type T to implement the Display trait?
easy
A. fn print_value(value: T) where Display { println!("{}", value); }
B. fn print_value<T>(value: T) where T: Display { println!("{}", value); }
C. fn print_value<T>(value: T: Display) { println!("{}", value); }
D. fn print_value(value: T) { println!("{}", value); }

Solution

  1. Step 1: Recall generic syntax with trait bounds

    The correct syntax places the trait bound after the generic type with a colon: T: Display.
  2. Step 2: Check function signature correctness

    fn print_value(value: T) { println!("{}", value); } correctly uses fn print_value(value: T). fn print_value<T>(value: T) where T: Display { println!("{}", value); } uses where clause but incorrectly placed. fn print_value<T>(value: T: Display) { println!("{}", value); } and D have syntax errors.
  3. Final Answer:

    fn print_value<T: Display>(value: T) { println!("{}", value); } -> Option D
  4. Quick Check:

    Generic with trait bound syntax = fn print_value(value: T) { println!("{}", value); } [OK]
Hint: Trait bounds go after generic type with colon: T: Trait [OK]
Common Mistakes:
  • Placing trait bound inside function parameters
  • Misusing where clause syntax
  • Omitting trait bound for required behavior
3. What will be the output of the following Rust code?
use std::fmt::Display;

fn print_info(item: T) {
    println!("Item: {}", item);
}

fn main() {
    print_info(42);
    print_info("hello");
}
medium
A. Item: 42 Item: hello
B. Item: 42 Item: "hello"
C. Compilation error due to missing trait implementation
D. Runtime error

Solution

  1. Step 1: Check trait implementation for types

    Both i32 (42) and &str ("hello") implement the Display trait, so the function can print both.
  2. Step 2: Understand println! macro output

    The macro prints the value without quotes for Display. So output is two lines: "Item: 42" and "Item: hello".
  3. Final Answer:

    Item: 42 Item: hello -> Option A
  4. Quick Check:

    Display trait prints values plainly = Item: 42 Item: hello [OK]
Hint: Display prints values without quotes, works for i32 and &str [OK]
Common Mistakes:
  • Expecting quotes around string output
  • Thinking trait is not implemented for primitive types
  • Confusing compile and runtime errors
4. Identify the error in the following Rust code and select the correct fix:
use std::fmt::Display;

fn print_twice<T>(item: T) {
    println!("{} {}", item, item);
}

fn main() {
    print_twice(10);
}
medium
A. Add trait bound: fn print_twice(item: T) {...}
B. Change println! to println!("{:?} {:?}", item, item);
C. Remove generic and use i32 directly
D. No error, code runs fine

Solution

  1. Step 1: Understand trait requirements for println!

    The format string "{}" requires the type to implement Display trait.
  2. Step 2: Check generic function signature

    The function lacks a trait bound on T, so compiler cannot guarantee T implements Display.
  3. Step 3: Fix by adding trait bound

    Add T: Display to function signature to fix the error.
  4. Final Answer:

    Add trait bound: fn print_twice<T: Display>(item: T) {...} -> Option A
  5. Quick Check:

    Format string "{}" needs Display trait bound [OK]
Hint: Add trait bound when using {} in println! with generics [OK]
Common Mistakes:
  • Ignoring missing trait bound error
  • Using {:?} without Debug trait bound
  • Assuming generic works without constraints
5. Given the following trait and struct, how can you implement a generic function compare_and_print that accepts any two items of the same type implementing both PartialOrd and Display, and prints which one is greater or if they are equal?
use std::fmt::Display;

struct Item<T> {
    value: T,
}

// Implement compare_and_print here
hard
A. fn compare_and_print(a: T, b: T) { println!("Comparing {} and {}", a, b); }
B. fn compare_and_print<T>(a: T, b: T) where T: PartialOrd + Display { if a >= b { println!("{} is greater", a); } else { println!("{} is greater", b); } }
C. fn compare_and_print(a: T, b: T) { if a > b { println!("{} is greater", a); } else if a < b { println!("{} is greater", b); } else { println!("Both are equal: {}", a); } }
D. fn compare_and_print(a: T, b: T) { if a > b { println!("a is greater"); } else { println!("b is greater"); } }

Solution

  1. Step 1: Define trait bounds for generic function

    The function must require T to implement both PartialOrd (for comparison) and Display (for printing).
  2. Step 2: Implement comparison logic with all cases

    Check if a > b, print a is greater; else if a < b, print b is greater; else print both are equal.
  3. Step 3: Verify printing uses Display trait

    Use {} in println! to print values, which requires Display.
  4. Final Answer:

    fn compare_and_print<T: PartialOrd + Display>(a: T, b: T) { if a > b { println!("{} is greater", a); } else if a < b { println!("{} is greater", b); } else { println!("Both are equal: {}", a); } } -> Option C
  5. Quick Check:

    Use PartialOrd + Display for comparison and printing [OK]
Hint: Use T: PartialOrd + Display to compare and print generics [OK]
Common Mistakes:
  • Omitting one of the required trait bounds
  • Not handling equality case
  • Using incorrect comparison operators
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