1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-05 22:19:01 +02:00
Files
comprehensive-rust/src/methods-and-traits/exercise.rs

52 lines
1.4 KiB
Rust
Raw Normal View History

// Copyright 2024 Google LLC
2022-12-21 16:36:30 +01:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
2022-12-21 16:36:30 +01:00
// ANCHOR: setup
pub trait Logger {
/// Log a message at the given verbosity level.
fn log(&self, verbosity: u8, message: &str);
2022-12-21 16:36:30 +01:00
}
struct StderrLogger;
2022-12-21 16:36:30 +01:00
impl Logger for StderrLogger {
fn log(&self, verbosity: u8, message: &str) {
eprintln!("verbosity={verbosity}: {message}");
2022-12-21 16:36:30 +01:00
}
}
/// Only log messages up to the given verbosity level.
struct VerbosityFilter {
max_verbosity: u8,
inner: StderrLogger,
2022-12-21 16:36:30 +01:00
}
// ANCHOR_END: setup
2022-12-21 16:36:30 +01:00
impl Logger for VerbosityFilter {
fn log(&self, verbosity: u8, message: &str) {
if verbosity <= self.max_verbosity {
self.inner.log(verbosity, message);
2022-12-21 16:36:30 +01:00
}
}
}
// ANCHOR: main
fn main() {
let logger = VerbosityFilter { max_verbosity: 3, inner: StderrLogger };
logger.log(5, "FYI");
logger.log(2, "Uhoh");
2022-12-21 16:36:30 +01:00
}
// ANCHOR_END: main