Why are traits used in Rust programming?
Think about how Rust allows different types to share common actions.
Traits let you define behavior that multiple types can share. This helps write flexible and reusable code by allowing polymorphism.
What is the output of this Rust code?
trait Greet {
fn greet(&self) -> String;
}
struct Dog;
impl Greet for Dog {
fn greet(&self) -> String {
String::from("Woof!")
}
}
fn main() {
let pet = Dog;
println!("{}", pet.greet());
}Look at the implementation of the greet method for Dog.
The Dog struct implements the Greet trait with greet returning "Woof!". So printing pet.greet() outputs "Woof!".
Consider this Rust code snippet. Why does it fail to compile?
trait Speak {
fn speak(&self) -> String;
}
struct Cat;
fn main() {
let kitty = Cat;
println!("{}", kitty.speak());
}Check if Cat has the required trait implementation.
The Cat struct does not implement the Speak trait, so calling kitty.speak() causes a compile error because the method is not found.
Which option contains the correct syntax to implement a trait in Rust?
trait Fly {
fn fly(&self) -> String;
}
struct Bird;
// Implementation options belowCheck the syntax for impl Trait for Type and method signature.
Option A correctly implements the trait Fly for Bird with the right syntax and method signature. Other options have syntax errors or wrong method signatures.
Given the trait Shape with a method area, which option correctly uses a vector of different shapes to calculate total area?
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
struct Square {
side: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
}
fn total_area(shapes: &Vec<Box<dyn Shape>>) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
// Which option correctly creates the vector and calls total_area?
}Remember Rust requires trait objects to be behind pointers like Box<dyn Trait>.
Option B correctly uses Vec to hold different shapes and calls total_area. Option B fails because traits cannot be used as concrete types. Option B uses references but the function expects boxed trait objects. Option B uses Box which is invalid syntax; it must be Box<dyn Shape>.