What is the output of this Rust program?
trait Greet {
fn greet(&self) {
println!("Hello from the 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 the 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();
}Check if the trait method is overridden in the implementation.
The Dog struct implements Speak and overrides the speak method. So calling d.speak() prints "Woof!".
What error does this Rust code produce?
trait Calculate {
fn calculate(&self, x: i32) -> i32;
}
struct Calculator;
impl Calculate for Calculator {
fn calculate(&self, x: i32) -> i32 {
42
}
}
fn main() {
let calc = Calculator;
println!("{}", calc.calculate(10));
}Compare the trait method signature with the implementation.
The trait method calculate expects a parameter x: i32 and returns i32. The implementation must match this signature. The original code missed the parameter and return type, causing a signature mismatch error. The fixed code compiles and prints 42.
Given this Rust code, what is the output?
trait Animal {
fn sound(&self);
}
struct Cat;
impl Animal for Cat {
fn sound(&self) {
println!("Meow");
}
}
fn make_sound(animal: &dyn Animal) {
animal.sound();
}
fn main() {
let c = Cat;
make_sound(&c);
}Consider how trait objects work with dynamic dispatch.
The function make_sound takes a reference to a trait object &dyn Animal. The call animal.sound() uses dynamic dispatch and calls Cat's implementation, printing "Meow".
Which of the following Rust trait definitions is syntactically correct?
Check the correct order and syntax for associated types in traits.
Option B is the only syntactically correct definition. In Rust traits, an associated type must be declared before it can be referenced (as `Self::Item`) in method signatures. Options A and C reference `Self::Item` before declaring `type Item`, causing a compilation error (`associated type not found for `Self``). Option B declares the type first but uses unqualified `Item` in the method signature, which cannot resolve to `Self::Item`.