Complete the code to define a trait named `Speak`.
trait [1] {
fn speak(&self);
}trait keyword.The trait is named Speak as required.
Complete the code to implement the `Speak` trait for struct `Dog`.
struct Dog; impl [1] for Dog { fn speak(&self) { println!("Woof!"); } }
for keyword.We implement the Speak trait for the Dog struct.
Fix the error in the trait method signature to make it a default method.
trait Speak {
fn speak(&self) [1] {
println!("Hello!");
}
}default which is not valid here.Default method implementations use curly braces {} instead of a semicolon.
Fill both blanks to define a trait with a method that returns a string slice.
trait [1] { fn name(&self) -> [2]; }
String instead of &str for the return type.& in the return type.The trait is named Named and the method returns a string slice &str.
Fill all three blanks to implement the `Named` trait for struct `Person`.
struct Person {
name: String,
}
impl [1] for Person {
fn name(&self) -> [2] {
&self.[3]
}
}String instead of &str.We implement the Named trait for Person. The method returns a string slice &str referencing the name field.
