Skip to content

Latest commit

 

History

History
27 lines (21 loc) · 1 KB

File metadata and controls

27 lines (21 loc) · 1 KB

Solution

{{#include exercise.rs:solution}}

The solution demonstrates how traits enable polymorphic behavior through composition:

  • Trait Implementation: VerbosityFilter implements the Logger trait, allowing it to be used anywhere a Logger is expected.
  • Wrapper Pattern: The VerbosityFilter struct wraps an instance of StderrLogger. It intercepts the log call 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 VerbosityFilter is hardcoded to wrap StderrLogger, it could be made generic to wrap any type that implements Logger. This is covered in the next section.