What is the output of this Rust code?
trait Greet {
fn greet(&self) {
println!("Hello from default method!");
}
}
struct Person;
impl Greet for Person {}
fn main() {
let p = Person;
p.greet();
}Check if the trait method has a default implementation and if the struct implements the trait without overriding the method.
The trait Greet provides a default implementation for greet. The struct Person implements Greet but does not override greet. So calling p.greet() uses the default method and prints the message.
What will this Rust program print?
trait Animal {
fn sound(&self) {
println!("Some generic sound");
}
}
struct Dog;
impl Animal for Dog {
fn sound(&self) {
println!("Bark");
}
}
fn main() {
let d = Dog;
d.sound();
}Look if the trait method is overridden in the implementation.
The Dog struct overrides the default sound method from Animal. So calling d.sound() prints "Bark".
Consider this Rust code. Why does it fail to compile?
trait Calculator {
fn calculate(&self) -> i32;
fn double(&self) -> i32 {
self.calculate() * 2
}
}
struct MyCalc;
impl Calculator for MyCalc {}
fn main() {
let c = MyCalc;
println!("{}", c.double());
}Check if all required trait methods are implemented.
The trait Calculator requires calculate to be implemented. MyCalc does not implement it, so compilation fails. The default method double calls calculate, but that does not provide an implementation.
What is the main purpose of providing default method implementations in Rust traits?
Think about code reuse and flexibility in trait design.
Default method implementations let traits provide common behavior that implementors can use directly or override with their own version. This promotes code reuse and flexibility.
What is the output of this Rust program?
trait Speaker {
fn speak(&self) {
println!("Default speak");
}
}
struct Cat;
impl Speaker for Cat {
fn speak(&self) {
println!("Meow");
}
}
struct Robot;
impl Speaker for Robot {}
fn main() {
let animals: Vec<&dyn Speaker> = vec![&Cat, &Robot];
for animal in animals {
animal.speak();
}
}Check which structs override the speak method and which use the default.
Cat overrides speak to print "Meow". Robot uses the default speak method which prints "Default speak". The vector holds trait objects, so calling speak calls the correct method for each.