The generic type T requires the Display trait to print values with {}.
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.
Final Answer:
Value: 10
Value: hello -> Option C
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
Step 1: Check operator usage on generic type
The + operator requires the type T to implement the Add trait.
Step 2: Identify missing trait bound
The function lacks T: std::ops::Add<Output = T> bound, causing a compile error.
Final Answer:
Missing trait bound for + operator on T -> Option A
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
Step 1: Identify required trait for comparison
To compare two values with >, the type T must implement PartialOrd.
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.
Final Answer:
fn largest<T: PartialOrd>(a: T, b: T) -> T { if a > b { a } else { b } } -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.