Complete the code to define a trait with a default method implementation.
trait Greet {
fn say_hello(&self) {
println!("[1]!");
}
}The default method say_hello prints "Hello!" using println!.
Complete the code to override the default method in the struct implementation.
struct Person; impl Greet for Person { fn say_hello(&self) { println!("[1]!"); } }
impl Greet for Person block.The Person struct overrides the default say_hello method to print "Hi there!".
Fix the error in the trait method signature to allow a default implementation.
trait Farewell {
fn say_goodbye(&self) -> [1] {
println!("Goodbye!");
}
}The method returns nothing, so the return type should be () (unit type) to allow a default implementation with println!.
Fill both blanks to define a trait with a default method that returns a string slice.
trait Describe {
fn description(&self) -> [1] {
[2]
}
}String instead of &str as return type.The method returns a string slice &str and the default return value is "Default description".
Fill all three blanks to implement a trait with a default method that uses a generic type and returns a formatted string.
trait Info {
fn info<T: ToString>(&self, value: T) -> [1] {
format!("Value: [2]", value[3])
}
}&str as return type but returning a formatted string.The method returns a String. The format string uses {} as placeholder, and value.to_string() converts the generic value to a string.