0
0
Rustprogramming~10 mins

Trait bounds in Rust - Interactive Code Practice

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

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

Rust
fn print_value<T: [1]>(value: T) {
    println!("{}", value);
}
Drag options to blanks, or click blank then click option'
ADisplay
BClone
CCopy
DDebug
Attempts:
3 left
💡 Hint
Common Mistakes
Using Clone or Copy traits which do not support formatting with {}.
Using Debug trait which requires {:?} formatting instead.
2fill in blank
medium

Complete the code to add a trait bound requiring T to implement both Display and Clone.

Rust
fn clone_and_print<T: [1] + Clone>(value: T) {
    let _copy = value.clone();
    println!("{}", value);
}
Drag options to blanks, or click blank then click option'
AClone
BCopy
CDebug
DDisplay
Attempts:
3 left
💡 Hint
Common Mistakes
Using Copy instead of Display for printing.
Omitting Display trait bound.
3fill in blank
hard

Fix the error in the function signature by adding the correct trait bound for T to be printable with {:?}.

Rust
fn debug_print<T: [1]>(value: T) {
    println!("{:?}", value);
}
Drag options to blanks, or click blank then click option'
ADisplay
BDebug
CClone
DCopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using Display trait which requires {} formatting.
Omitting any trait bound causing compile error.
4fill in blank
hard

Fill both blanks to define a function that accepts any type T implementing both Debug and PartialEq traits.

Rust
fn compare_and_print<T: [1] + [2]>(a: T, b: T) {
    if a == b {
        println!("Equal: {:?}", a);
    } else {
        println!("Not equal: {:?} and {:?}", a, b);
    }
}
Drag options to blanks, or click blank then click option'
ADebug
BDisplay
CPartialEq
DClone
Attempts:
3 left
💡 Hint
Common Mistakes
Using Display instead of Debug for printing.
Omitting PartialEq causing comparison error.
5fill in blank
hard

Fill both blanks to create a function that returns the larger of two values implementing PartialOrd and Debug.

Rust
fn max_value<T: [1] + [2]>(a: T, b: T) -> T {
    if a > b {
        println!("Max is {:?}", a);
        a
    } else {
        println!("Max is {:?}", b);
        b
    }
}
Drag options to blanks, or click blank then click option'
APartialOrd
BCopy
CDebug
DClone
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting PartialOrd causing comparison error.
Using Display instead of Debug for printing.