Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'dyn' keyword before the trait name.
Using the trait name without a reference.
✗ Incorrect
Trait objects in Rust are declared using the 'dyn' keyword followed by the trait name, like 'dyn Display'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the 'dyn' keyword inside the Box.
Using the trait name without 'dyn' in Box.
✗ Incorrect
Boxed trait objects use 'Box' syntax to store values on the heap with dynamic dispatch.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the trait name without 'dyn'.
Using a reference to the trait without 'dyn'.
✗ Incorrect
Trait objects must be referenced with 'dyn' keyword, so '&dyn Debug' is the correct type for dynamic dispatch.
4fill in blank
hardFill 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'
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.
✗ Incorrect
The vector holds boxed 'dyn Display' trait objects, and calling 'to_string()' converts them to strings for printing.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different trait objects in return type and variable.
Omitting 'dyn' keyword in trait object types.
✗ Incorrect
The function returns a boxed 'dyn Debug' trait object, so all blanks must be 'dyn Debug' to match the type.