Solution

  1. pub trait Logger {
  2.     /// Log a message at the given verbosity level.
  3.     fn log(&self, verbosity: u8, message: &str);
  4. }
  5. struct StdoutLogger;
  6. impl Logger for StdoutLogger {
  7.     fn log(&self, verbosity: u8, message: &str) {
  8.         println!("verbosity={verbosity}: {message}");
  9.     }
  10. }
  11. /// Only log messages up to the given verbosity level.
  12. struct VerbosityFilter {
  13.     max_verbosity: u8,
  14.     inner: StdoutLogger,
  15. }
  16. impl Logger for VerbosityFilter {
  17.     fn log(&self, verbosity: u8, message: &str) {
  18.         if verbosity <= self.max_verbosity {
  19.             self.inner.log(verbosity, message);
  20.         }
  21.     }
  22. }
  23. fn main() {
  24.     let logger = VerbosityFilter { max_verbosity: 3, inner: StdoutLogger };
  25.     logger.log(5, "FYI");
  26.     logger.log(2, "Uhoh");
  27. }