1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-03 21:39:51 +02:00

Replace GUI exercise with Logger (#1682)

This should be a bit simpler, and notably
* does not require trait objects, which per #1516 should be moved later
in the course
 * does not require a lot of futzing with string formatting

But all that hard work developing the GUI exercise is not for naught: it
remains in the "Modules" segment, where students will get a chance to
read some Rust code and reorganize it a little bit.

Fixes #1617.

R=mgeisler as the original author of the GUI exercise.
This commit is contained in:
Dustin J. Mitchell
2024-01-18 14:15:19 -05:00
committed by GitHub
parent b4164e44a3
commit 9d9b4170e4
8 changed files with 202 additions and 178 deletions

9
src/modules/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "modules"
version = "0.1.0"
edition = "2021"
publish = false
[[bin]]
name = "modules"
path = "exercise.rs"

View File

@ -1,16 +1,15 @@
---
minutes: 20
minutes: 15
---
# Exercise: Modules for the GUI Library
# Exercise: Modules for a GUI Library
In this exercise, you will reorganize the GUI Library exercise from the "Methods
and Traits" segment of the course into a collection of modules. It is typical to
put each type or set of closely-related types into its own module, so each
widget type should get its own module.
In this exercise, you will reorganize a small GUI Library implementation. This
library defines a `Widget` trait and a few implementations of that trait, as
well as a `main` function.
If you no longer have your version, that's fine - refer back to the
[provided solution](../methods-and-traits/solution.html).
It is typical to put each type or set of closely-related types into its own
module, so each widget type should get its own module.
## Cargo Setup
@ -23,8 +22,16 @@ cd gui-modules
cargo run
```
Edit `src/main.rs` to add `mod` statements, and add additional files in the
`src` directory.
Edit the resulting `src/main.rs` to add `mod` statements, and add additional
files in the `src` directory.
## Source
Here's the single-module implementation of the GUI library:
```rust
{{#include exercise.rs:single-module}}
```
<details>

132
src/modules/exercise.rs Normal file
View File

@ -0,0 +1,132 @@
// Copyright 2022 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: single-module
pub trait Widget {
/// Natural width of `self`.
fn width(&self) -> usize;
/// Draw the widget into a buffer.
fn draw_into(&self, buffer: &mut dyn std::fmt::Write);
/// Draw the widget on standard output.
fn draw(&self) {
let mut buffer = String::new();
self.draw_into(&mut buffer);
println!("{buffer}");
}
}
pub struct Label {
label: String,
}
impl Label {
fn new(label: &str) -> Label {
Label { label: label.to_owned() }
}
}
pub struct Button {
label: Label,
}
impl Button {
fn new(label: &str) -> Button {
Button { label: Label::new(label) }
}
}
pub struct Window {
title: String,
widgets: Vec<Box<dyn Widget>>,
}
impl Window {
fn new(title: &str) -> Window {
Window { title: title.to_owned(), widgets: Vec::new() }
}
fn add_widget(&mut self, widget: Box<dyn Widget>) {
self.widgets.push(widget);
}
fn inner_width(&self) -> usize {
std::cmp::max(
self.title.chars().count(),
self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
)
}
}
impl Widget for Window {
fn width(&self) -> usize {
// Add 4 paddings for borders
self.inner_width() + 4
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let mut inner = String::new();
for widget in &self.widgets {
widget.draw_into(&mut inner);
}
let inner_width = self.inner_width();
// TODO: Change draw_into to return Result<(), std::fmt::Error>. Then use the
// ?-operator here instead of .unwrap().
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
writeln!(buffer, "| {:^inner_width$} |", &self.title).unwrap();
writeln!(buffer, "+={:=<inner_width$}=+", "").unwrap();
for line in inner.lines() {
writeln!(buffer, "| {:inner_width$} |", line).unwrap();
}
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
}
}
impl Widget for Button {
fn width(&self) -> usize {
self.label.width() + 8 // add a bit of padding
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let width = self.width();
let mut label = String::new();
self.label.draw_into(&mut label);
writeln!(buffer, "+{:-<width$}+", "").unwrap();
for line in label.lines() {
writeln!(buffer, "|{:^width$}|", &line).unwrap();
}
writeln!(buffer, "+{:-<width$}+", "").unwrap();
}
}
impl Widget for Label {
fn width(&self) -> usize {
self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0)
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
writeln!(buffer, "{}", &self.label).unwrap();
}
}
fn main() {
let mut window = Window::new("Rust GUI Demo 1.23");
window.add_widget(Box::new(Label::new("This is a small text GUI demo.")));
window.add_widget(Box::new(Button::new("Click me!")));
window.draw();
}