0
0
Rustprogramming~10 mins

Defining traits 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 trait named `Speak`.

Rust
trait [1] {
    fn speak(&self);
}
Drag options to blanks, or click blank then click option'
ASpeak
BTalk
CSay
DVoice
Attempts:
3 left
💡 Hint
Common Mistakes
Using a struct name instead of a trait name.
Forgetting to use the trait keyword.
2fill in blank
medium

Complete the code to implement the `Speak` trait for struct `Dog`.

Rust
struct Dog;

impl [1] for Dog {
    fn speak(&self) {
        println!("Woof!");
    }
}
Drag options to blanks, or click blank then click option'
AAnimal
BSound
CSpeak
DTalk
Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct name instead of the trait name in the impl block.
Forgetting the for keyword.
3fill in blank
hard

Fix the error in the trait method signature to make it a default method.

Rust
trait Speak {
    fn speak(&self) [1] {
        println!("Hello!");
    }
}
Drag options to blanks, or click blank then click option'
A{}
B-> ()
Cdefault
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Ending the method signature with a semicolon when providing a default implementation.
Using the keyword default which is not valid here.
4fill in blank
hard

Fill both blanks to define a trait with a method that returns a string slice.

Rust
trait [1] {
    fn name(&self) -> [2];
}
Drag options to blanks, or click blank then click option'
ANamed
B&str
CString
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of &str for the return type.
Forgetting the reference symbol & in the return type.
5fill in blank
hard

Fill all three blanks to implement the `Named` trait for struct `Person`.

Rust
struct Person {
    name: String,
}

impl [1] for Person {
    fn name(&self) -> [2] {
        &self.[3]
    }
}
Drag options to blanks, or click blank then click option'
ANamed
B&str
Cname
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Returning String instead of &str.
Using the wrong field name or forgetting the reference symbol.