0
0
Rustprogramming~20 mins

Why traits are used in Rust - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Traits Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Purpose of Traits in Rust

Why are traits used in Rust programming?

ATo enforce variable immutability throughout the program.
BTo allocate memory dynamically for variables at runtime.
CTo replace all functions with macros for faster execution.
DTo define shared behavior that different types can implement, enabling polymorphism.
Attempts:
2 left
💡 Hint

Think about how Rust allows different types to share common actions.

Predict Output
intermediate
1:30remaining
Output of Trait Implementation

What is the output of this Rust code?

Rust
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());
}
AWoof!
BHello!
CCompilation error: missing trait implementation
DRuntime error: method not found
Attempts:
2 left
💡 Hint

Look at the implementation of the greet method for Dog.

🔧 Debug
advanced
2:00remaining
Why does this trait code fail to compile?

Consider this Rust code snippet. Why does it fail to compile?

Rust
trait Speak {
    fn speak(&self) -> String;
}

struct Cat;

fn main() {
    let kitty = Cat;
    println!("{}", kitty.speak());
}
AThe println! macro is used incorrectly without format specifiers.
BThe trait Speak is missing a default implementation for speak method.
CCat does not implement the Speak trait, so the method speak is not found.
DThe struct Cat must be mutable to call speak method.
Attempts:
2 left
💡 Hint

Check if Cat has the required trait implementation.

📝 Syntax
advanced
2:00remaining
Identify the Syntax Error in Trait Implementation

Which option contains the correct syntax to implement a trait in Rust?

Rust
trait Fly {
    fn fly(&self) -> String;
}

struct Bird;

// Implementation options below
A
impl Fly for Bird {
    fn fly(&self) -> String {
        String::from("I am flying!")
    }
}
B
impl Fly Bird {
    fn fly(&self) -> String {
        String::from("I am flying!")
    }
}
C
impl Fly for Bird {
    fn fly() -> String {
        String::from("I am flying!")
    }
}
D
impl Fly for Bird {
    fn fly(&self) {
        println!("I am flying!");
    }
}
Attempts:
2 left
💡 Hint

Check the syntax for impl Trait for Type and method signature.

🚀 Application
expert
2:30remaining
Using Traits for Polymorphism

Given the trait Shape with a method area, which option correctly uses a vector of different shapes to calculate total area?

Rust
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?
}
A
;))sepahs&amp;(aera_latot ,"}{"(!nltnirp
;])} 0.3 :edis { erauqS(wen::xoB ,)} 0.2 :suidar { elcriC(wen::xoB[!cev = &gt;&gt;epahS nyd&lt;xoB&lt;ceV :sepahs tel
B
let shapes: Vec&lt;Box&lt;dyn Shape&gt;&gt; = vec![Box::new(Circle { radius: 2.0 }), Box::new(Square { side: 3.0 })];
println!("{}", total_area(&amp;shapes));
C
let shapes: Vec&lt;&amp;dyn Shape&gt; = vec![&amp;Circle { radius: 2.0 }, &amp;Square { side: 3.0 }];
println!("{}", total_area(&amp;shapes));
D
let shapes: Vec&lt;Shape&gt; = vec![Circle { radius: 2.0 }, Square { side: 3.0 }];
println!("{}", total_area(&amp;shapes));
Attempts:
2 left
💡 Hint

Remember Rust requires trait objects to be behind pointers like Box<dyn Trait>.