{{#include exercise.rs:solution}}The solution demonstrates how traits enable polymorphic behavior through composition:
- Trait Implementation:
VerbosityFilterimplements theLoggertrait, allowing it to be used anywhere aLoggeris expected. - Wrapper Pattern: The
VerbosityFilterstruct wraps an instance ofStderrLogger. It intercepts thelogcall to apply filtering logic before delegating to the inner logger. - Composition over Inheritance: Behavior is extended by wrapping one type in another, rather than through a class hierarchy.
Details
- Extensibility: This wrapper pattern (often called a decorator or middleware) allows adding functionality like filtering, buffering, or timestamping without modifying the underlying logger.
- Teaser for Generics: While
VerbosityFilteris hardcoded to wrapStderrLogger, it could be made generic to wrap any type that implementsLogger. This is covered in the next section.