解答

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