1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-05 14:10:29 +02:00
Files
comprehensive-rust/src/methods-and-traits/exercise.rs
Dustin J. Mitchell b3c57e4cbf Be clear that the methods-and-traits exercise does not require generics (#2568)
When teaching the course, I got a little tripped up thinking students
would need to make the `VerbosityFilter` generic over `Logger`. Let's be
clearer that this is not required, and will be described later.

This also updates the generic-types slide to repeat the exercise,
completing that thought.
2025-01-23 09:40:59 +01:00

52 lines
1.4 KiB
Rust

// Copyright 2024 Google LLC
//
// 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
// ANCHOR: setup
pub trait Logger {
/// Log a message at the given verbosity level.
fn log(&self, verbosity: u8, message: &str);
}
struct StderrLogger;
impl Logger for StderrLogger {
fn log(&self, verbosity: u8, message: &str) {
eprintln!("verbosity={verbosity}: {message}");
}
}
/// Only log messages up to the given verbosity level.
struct VerbosityFilter {
max_verbosity: u8,
inner: StderrLogger,
}
// ANCHOR_END: setup
impl Logger for VerbosityFilter {
fn log(&self, verbosity: u8, message: &str) {
if verbosity <= self.max_verbosity {
self.inner.log(verbosity, message);
}
}
}
// ANCHOR: main
fn main() {
let logger = VerbosityFilter { max_verbosity: 3, inner: StderrLogger };
logger.log(5, "FYI");
logger.log(2, "Uhoh");
}
// ANCHOR_END: main