What is a Default Trait Implementation in Rust?
Did you know that trait definitions can contain a complete method definition? I didn’t. I thought it could only contain a signature.
I wasn’t quite clear on what a Default implementation vs. implementing it on the struct directly. I would imagine I won’t be alone on this, so here is what I found while tinkering with Traits.
Case By Case Implementation
When I first started tinkering with traits, this was the only sort of trait implementation I understood. In code it looks like this:
Above I directly implemented the trait beneath the place where the trait itself was defined. This is what I’m referring to as case by case. In each place where the trait is programmed to be used, method definitions are required since the trait definition itself has only a function signature and no real function definition.
This is effectively creating custom implementations for that struct, which is great! That’s the whole reason why I began investigating traits in the first place. I wanted to have the power of “Object instance composition” in Rust.
I had no idea I could define a function directly in the trait itself!
Define Methods In The Trait
On the other hand, when you use the default implementation of traits in Rust, it allows the definition of methods in the trait definition itself, so specifying its behavior for each struct implementation is not needed.
In this above snippet, you can see the trait itself has all the definitions needed for a given function. But can still be overwritten if needed.
The compiler must still be told to implement the trait for the struct though.
impl GreetingNodeDefault for MenuNode {}
I think this will be great for reducing boilerplate code, and it feels super elegant to me. Good vibes rust.
Conclusion
In order to implement default trait methods, the trait must have functions defined within its own definition, and not just function signatures. And implementing default trait behavior requires no additional boilerplate code other than telling the rust compiler that there will be a trait implemented for a given struct.