0
0
Rustprogramming~5 mins

Default method implementations in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a default method implementation in Rust traits?
A default method implementation in Rust traits is a method defined inside a trait with a body. Types implementing the trait can use this default method without needing to provide their own version.
Click to reveal answer
beginner
How do you override a default method implementation in Rust?
To override a default method, the implementing type provides its own method with the same name and signature inside the impl block for the trait.
Click to reveal answer
intermediate
Why are default method implementations useful in Rust?
They allow trait authors to provide common behavior that many types can share, reducing code duplication and making it easier to add new methods without breaking existing implementations.
Click to reveal answer
beginner
Can a trait have methods without default implementations?
Yes. Traits can have methods without default implementations, which must be implemented by any type that implements the trait.
Click to reveal answer
beginner
Show a simple Rust trait with a default method implementation.
```rust
trait Greet {
    fn say_hello(&self) {
        println!("Hello from default method!");
    }
}

struct Person;

impl Greet for Person {}

fn main() {
    let p = Person;
    p.say_hello(); // Prints: Hello from default method!
}
```
Click to reveal answer
What happens if a type implementing a trait does NOT override a default method?
AThe default method implementation is used.
BCompilation fails with an error.
CThe method is ignored and not available.
DThe program crashes at runtime.
Which keyword is used to define a trait in Rust?
Afn
Bstruct
Cimpl
Dtrait
Can a default method in a trait call other methods of the same trait?
ANo, it can only use its own code.
BYes, including methods without default implementations.
COnly if those methods are also default methods.
DOnly if the trait is marked as 'default'.
What must a type do if a trait method has no default implementation?
ANothing, it can skip implementing it.
BMark the method as optional.
CProvide its own implementation of that method.
DUse the default method from another trait.
Which of these is a benefit of default method implementations?
AThey allow code reuse and easier trait evolution.
BThey force all types to implement every method.
CThey prevent overriding methods.
DThey make traits slower to compile.
Explain what default method implementations are in Rust traits and why they are useful.
Think about how traits can provide behavior without forcing every type to write the same code.
You got /3 concepts.
    Describe how you would override a default method implementation in a Rust trait for a specific type.
    Consider how you customize behavior for your own types.
    You got /3 concepts.