0
0
Rustprogramming~10 mins

Trait objects overview 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 declare a trait object reference.

Rust
fn print_value(value: &[1]) {
    println!("Value printed");
}
Drag options to blanks, or click blank then click option'
Adyn Display
BDisplay
C&Display
Ddyn Trait
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'dyn' keyword before the trait name.
Using the trait name without a reference.
2fill in blank
medium

Complete the code to create a boxed trait object.

Rust
let boxed: Box<[1]> = Box::new(5);
Drag options to blanks, or click blank then click option'
ADisplay
Bdyn Debug
Cdyn Display
DDebug
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the 'dyn' keyword inside the Box.
Using the trait name without 'dyn' in Box.
3fill in blank
hard

Fix the error in the function signature to accept any trait object implementing Debug.

Rust
fn debug_print(value: &[1]) {
    println!("{:?}", value);
}
Drag options to blanks, or click blank then click option'
ADebug
B&Debug
Cdyn Display
Ddyn Debug
Attempts:
3 left
💡 Hint
Common Mistakes
Using the trait name without 'dyn'.
Using a reference to the trait without 'dyn'.
4fill in blank
hard

Fill both blanks to create a vector of boxed trait objects implementing Display.

Rust
let mut vec: Vec<Box<[1]>> = Vec::new();
vec.push(Box::new("hello"));
vec.push(Box::new(123));
for item in vec.iter() {
    println!("{}", item.[2]());
}
Drag options to blanks, or click blank then click option'
Adyn Display
Bdyn Debug
Cto_string
Dto_owned
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong trait in the vector type.
Calling a method that does not exist on the trait object.
5fill in blank
hard

Fill all three blanks to define a function returning a boxed trait object implementing Debug.

Rust
fn make_debug() -> Box<[1]> {
    let value = 42;
    Box::new(value) as Box<[2]>
}

fn main() {
    let debug_obj: Box<[3]> = make_debug();
    println!("{:?}", debug_obj);
}
Drag options to blanks, or click blank then click option'
Adyn Debug
Bdyn Display
Ddyn Any
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different trait objects in return type and variable.
Omitting 'dyn' keyword in trait object types.