What is the output of this Rust code?
trait Greet {
fn greet(&self) {
println!("Hello from trait!");
}
}
struct Person;
impl Greet for Person {}
fn main() {
let p = Person;
p.greet();
}Check if the trait method has a default implementation.
The trait Greet provides a default implementation for greet. Since Person implements Greet but does not override greet, the default method is called, printing "Hello from trait!".
What will this Rust program print?
trait Speak {
fn speak(&self) {
println!("Speaking from trait");
}
}
struct Dog;
impl Speak for Dog {
fn speak(&self) {
println!("Woof!");
}
}
fn main() {
let d = Dog;
d.speak();
}Look at whether the trait method is overridden in the implementation.
The Dog struct overrides the speak method from the Speak trait, so calling d.speak() prints "Woof!".
Identify the cause of the compilation error in this Rust code.
trait Calculate {
fn calculate(&self, x: i32) -> i32;
}
struct Calculator;
impl Calculate for Calculator {
fn calculate(&self, x: i32) -> i32 {
42
}
}
fn main() {
let c = Calculator;
println!("{}", c.calculate(10));
}Compare the method signatures in the trait and the implementation.
The trait Calculate requires a method calculate(&self, x: i32) -> i32. The implementation defines calculate(&self) without the parameter x, causing a signature mismatch and compilation error.
Given the trait Displayable and a generic struct Wrapper<T>, which implementation is syntactically correct?
trait Displayable {
fn display(&self) -> String;
}
struct Wrapper<T> {
value: T,
}Remember to include generic parameters in both impl and trait implementation.
Option D correctly uses impl<T> Displayable for Wrapper<T> and returns a String as required. Option D misses generic parameter T in impl. Option D misses <T> after Wrapper. Option D has wrong return type (missing String return).
Consider this Rust code using trait objects. What will it print?
trait Animal {
fn sound(&self) -> &'static str;
}
struct Cat;
struct Dog;
impl Animal for Cat {
fn sound(&self) -> &'static str {
"Meow"
}
}
impl Animal for Dog {
fn sound(&self) -> &'static str {
"Woof"
}
}
fn make_sound(animal: &dyn Animal) {
println!("{}", animal.sound());
}
fn main() {
let cat = Cat;
let dog = Dog;
let animals: Vec<&dyn Animal> = vec![&cat, &dog];
for a in animals {
make_sound(a);
}
}Look at the order of elements in the vector and how trait objects work.
The vector animals contains references to Cat then Dog. The loop calls make_sound for each, printing "Meow" then "Woof".