Bird
Raised Fist0
Rustprogramming~20 mins

Trait bounds in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Trait Bounds Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of function using trait bounds with multiple traits
What is the output of this Rust program?
Rust
use std::fmt::Display;

fn print_and_return<T: Display + Clone>(item: T) -> T {
    println!("Item: {}", item);
    item.clone()
}

fn main() {
    let x = print_and_return(42);
    println!("Returned: {}", x);
}
ACompilation error due to missing trait bound
BItem: 42\nReturned: 43
CItem: 42\nReturned: 42
DRuntime panic due to clone failure
Attempts:
2 left
💡 Hint
Check the trait bounds on the generic type T and what traits i32 implements.
❓ Predict Output
intermediate
2:00remaining
Output of function with trait bound using where clause
What is the output of this Rust code snippet?
Rust
fn describe<T>(item: T) where T: std::fmt::Debug {
    println!("Debug info: {:?}", item);
}

fn main() {
    describe("hello");
}
ADebug info: hello
BDebug info: "hello"
CCompilation error: missing trait bound
DRuntime error: cannot print debug
Attempts:
2 left
💡 Hint
Look at how the Debug trait formats strings with {:?}.
❓ Predict Output
advanced
2:00remaining
Output of generic function with trait bound and method call
What is the output of this Rust program?
Rust
trait Summary {
    fn summarize(&self) -> String;
}

struct NewsArticle {
    headline: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("Breaking news: {}", self.headline)
    }
}

fn notify<T: Summary>(item: T) {
    println!("Notification: {}", item.summarize());
}

fn main() {
    let article = NewsArticle { headline: String::from("Rust 1.70 released") };
    notify(article);
}
ANotification: Breaking news: Rust 1.70 released
BNotification: Rust 1.70 released
CCompilation error: trait method not found
DRuntime error: method call failed
Attempts:
2 left
💡 Hint
Check how the Summary trait is implemented and used in notify.
❓ Predict Output
advanced
2:00remaining
Output of function with multiple trait bounds and generic struct
What is the output of this Rust code?
Rust
use std::fmt::{Display, Debug};

struct Pair<T> {
    x: T,
    y: T,
}

impl<T: Display + Debug> Pair<T> {
    fn compare_and_display(&self) {
        if self.x == self.y {
            println!("Equal: {}", self.x);
        } else {
            println!("Not equal: {:?} and {:?}", self.x, self.y);
        }
    }
}

fn main() {
    let pair = Pair { x: 5, y: 5 };
    pair.compare_and_display();
}
ACompilation error: trait bound missing for PartialEq
BNot equal: 5 and 5
CEqual: 5
DRuntime error: cannot compare values
Attempts:
2 left
💡 Hint
Check which traits are required for the == operator.
🧠 Conceptual
expert
2:00remaining
Which option correctly explains trait bounds in Rust generics?
Which statement best describes the purpose of trait bounds in Rust generic functions or structs?
ATrait bounds are used to convert generic types into concrete types at compile time.
BTrait bounds automatically implement traits for all generic types used in the function or struct.
CTrait bounds restrict generic types to only primitive types like integers and floats.
DTrait bounds specify the required capabilities a generic type must have to use certain methods or operators.
Attempts:
2 left
💡 Hint
Think about why Rust needs trait bounds when calling methods on generic types.

Practice

(1/5)
1. What does a trait bound like T: Display mean in Rust?
easy
A. The generic type T cannot implement the Display trait.
B. The generic type T must implement the Display trait.
C. The function only accepts the Display type, not generics.
D. The trait Display is optional for T.

Solution

  1. Step 1: Understand trait bounds syntax

    In Rust, T: TraitName means the generic type T must implement the trait TraitName.
  2. Step 2: Apply to T: Display

    This means T must implement the Display trait to be used where this bound is required.
  3. Final Answer:

    The generic type T must implement the Display trait. -> Option B
  4. Quick Check:

    Trait bound T: Display means T implements Display [OK]
Hint: Trait bounds require the type to implement the trait [OK]
Common Mistakes:
  • Thinking trait bounds exclude the trait
  • Confusing trait bounds with type restrictions
  • Assuming trait bounds are optional
2. Which of the following is the correct syntax to add a trait bound for a generic type T that must implement the Clone trait in a function?
easy
A. fn example(value: T) {}
B. fn example(value: T) {}
C. fn example(value: T) {}
D. fn example(value: T) {}

Solution

  1. Step 1: Recall trait bound syntax

    The correct syntax to add a trait bound is T: TraitName, with a colon and capitalized trait name.
  2. Step 2: Check each option

    fn example(value: T) {} uses T: Clone which is correct. fn example(value: T) {} misses the colon. fn example(value: T) {} misuses where without proper syntax. fn example(value: T) {} uses lowercase clone, which is incorrect.
  3. Final Answer:

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

    Trait bound syntax uses colon and capitalized trait [OK]
Hint: Use colon and capitalized trait for bounds (T: Trait) [OK]
Common Mistakes:
  • Omitting colon between type and trait
  • Using lowercase trait names
  • Incorrect use of where without full syntax
3. What will be the output of this Rust code?
use std::fmt::Display;

fn print_value(value: T) {
    println!("Value: {}", value);
}

fn main() {
    print_value(42);
    print_value("hello");
}
medium
A. Value: 42\nValue: hello
B. Value: 42\nValue: "hello"
C. Compilation error because &str does not implement Display
D. Runtime error due to trait bound violation

Solution

  1. Step 1: Check trait bounds for types

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

    The macro prints the formatted string with the value. So it prints "Value: 42" and then "Value: hello" on separate lines.
  3. Final Answer:

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

    Both i32 and &str implement Display, so prints both values [OK]
Hint: Check if types implement the trait bound before calling [OK]
Common Mistakes:
  • Assuming &str does not implement Display
  • Expecting quotes around string output
  • Confusing compile and runtime errors
4. Identify the error in this Rust code snippet:
fn print_debug<T>(value: T) {
    println!("{:?}", value);
}

fn main() {
    print_debug(10);
}
medium
A. Missing trait bound T: Debug for value.
B. Incorrect macro usage, should use {} instead of {:?}.
C. Function should return a value, missing return type.
D. No error, code compiles and runs fine.

Solution

  1. Step 1: Understand the use of {:?} in println!

    The {:?} format specifier requires the type to implement the Debug trait.
  2. Step 2: Check function signature

    The function print_debug has no trait bound on T, so the compiler cannot guarantee T implements Debug.
  3. Final Answer:

    Missing trait bound T: Debug for value. -> Option A
  4. Quick Check:

    Using {:?} requires T: Debug trait bound [OK]
Hint: Add trait bound when using {:?} formatting [OK]
Common Mistakes:
  • Forgetting to add T: Debug bound
  • Using {:?} without Debug trait
  • Assuming all types implement Debug by default
5. You want to write a generic function that accepts any type T which implements both Clone and Debug traits. Which is the correct way to write the function signature?
hard
A. fn process(value: T) {}
B. fn process(value: T) {}
C. fn process<T>(value: T) where T: Clone + Debug {}
D. }{ )T :eulav(>gubeD + enolC :T

Solution

  1. Step 1: Understand trait bounds syntax

    You can specify multiple trait bounds using either T: Trait1 + Trait2 or a where clause like where T: Trait1 + Trait2.
  2. Step 2: Analyze options

    fn process(value: T) {} uses T: Clone + Debug which is correct. fn process(value: T) {} incorrectly separates traits with a comma. fn process<T>(value: T) where T: Clone + Debug {} uses a valid where clause. fn process(value: T) {} states "Both A and C are correct" which is not an option here, so only C is correct.
  3. Final Answer:

    fn process<T>(value: T) where T: Clone + Debug {} -> Option C
  4. Quick Check:

    Multiple trait bounds can be combined with + or where clause [OK]
Hint: Use + or where clause to combine trait bounds [OK]
Common Mistakes:
  • Separating trait bounds with commas instead of +
  • Confusing where clause syntax
  • Using only one trait bound when multiple needed
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