0
0
Rustprogramming~10 mins

Why traits are used in Rust - Test Your Understanding

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

Complete the code to define a trait named Printable.

Rust
trait Printable {
    fn [1](&self);
}
Drag options to blanks, or click blank then click option'
Aprint
Bdisplay
Coutput
Dshow
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names that are not conventional for printing.
2fill in blank
medium

Complete the code to implement the Printable trait for struct Book.

Rust
struct Book {
    title: String,
}

impl Printable for Book {
    fn [1](&self) {
        println!("Book: {}", self.title);
    }
}
Drag options to blanks, or click blank then click option'
Adisplay
Bprint
Cshow
Doutput
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name than the trait defines.
3fill in blank
hard

Fix the error in the code by completing the trait bound syntax.

Rust
fn print_item<T: [1]>(item: T) {
    item.print();
}
Drag options to blanks, or click blank then click option'
APrintable
BDisplay
CDebug
DClone
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated traits like Display or Debug.
4fill in blank
hard

Fill both blanks to create a trait and implement it for a struct.

Rust
trait [1] {
    fn print(&self);
}

struct Article {
    content: String,
}

impl [2] for Article {
    fn print(&self) {
        println!("Article: {}", self.content);
    }
}
Drag options to blanks, or click blank then click option'
APrintable
BDisplayable
DShowable
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for trait and impl.
5fill in blank
hard

Fill all three blanks to define a trait, implement it, and use it in a function.

Rust
trait [1] {
    fn print(&self);
}

struct Note {
    text: String,
}

impl [2] for Note {
    fn print(&self) {
        println!("Note: {}", self.text);
    }
}

fn show<T: [3]>(item: T) {
    item.print();
}
Drag options to blanks, or click blank then click option'
APrintable
DDisplay
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing trait names or using unrelated traits.