Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a trait named `Speak`.
Rust
trait [1] {
fn speak(&self);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a struct name instead of a trait name.
Forgetting to use the
trait keyword.✗ Incorrect
The trait is named Speak as required.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct name instead of the trait name in the impl block.
Forgetting the
for keyword.✗ Incorrect
We implement the Speak trait for the Dog struct.
3fill in blank
hardFix 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'
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.✗ Incorrect
Default method implementations use curly braces {} instead of a semicolon.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
String instead of &str for the return type.Forgetting the reference symbol
& in the return type.✗ Incorrect
The trait is named Named and the method returns a string slice &str.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning
String instead of &str.Using the wrong field name or forgetting the reference symbol.
✗ Incorrect
We implement the Named trait for Person. The method returns a string slice &str referencing the name field.