Recall & Review
beginner
What is a trait in Rust?
A trait in Rust is like a promise or a contract that a type can make. It defines a set of methods that the type must implement. Traits let us share behavior between different types.Click to reveal answer
beginner
How do you implement a trait for a struct in Rust?
You use the
impl TraitName for StructName syntax, then define the required methods inside curly braces. This tells Rust that the struct agrees to the trait's contract.Click to reveal answer
intermediate
Why use traits instead of just functions?
Traits let you write code that works with many types that share behavior. This is like saying: "Anything that can do this action can be used here," making your code flexible and reusable.Click to reveal answer
beginner
What happens if you don't implement all methods of a trait?
Rust will give a compile-time error. You must implement all required methods of a trait unless they have default implementations.
Click to reveal answer
intermediate
Can a trait have default method implementations?
Yes! Traits can provide default code for methods. Types can use these defaults or provide their own version by overriding the method.
Click to reveal answer
Which keyword is used to implement a trait for a struct in Rust?
✗ Incorrect
The
impl keyword is used to implement a trait for a struct.What will happen if a struct does not implement all required methods of a trait?
✗ Incorrect
Rust requires all trait methods to be implemented unless they have defaults, otherwise it gives a compile-time error.
Can traits in Rust provide default method implementations?
✗ Incorrect
Traits can include default method implementations that types can use or override.
What is the main benefit of using traits in Rust?
✗ Incorrect
Traits define shared behavior, allowing different types to be used interchangeably if they implement the trait.
How do you specify that a struct implements a trait named 'Speak'?
✗ Incorrect
The syntax
impl Speak for StructName { ... } is used to implement the trait.Explain in your own words what a trait is and why it is useful in Rust.
Think about how traits let different types promise to have certain methods.
You got /4 concepts.
Describe the steps to implement a trait for a struct, including what happens if you miss a required method.
Remember the syntax and Rust's strict checking.
You got /4 concepts.