1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-06 14:35:36 +02:00

Comprehensive Rust v2 (#1073)

I've taken some work by @fw-immunant and others on the new organization
of the course and condensed it into a form amenable to a text editor and
some computational analysis. You can see the inputs in `course.py` but
the interesting bits are the output: `outline.md` and `slides.md`.

The idea is to break the course into more, smaller segments with
exercises at the ends and breaks in between. So `outline.md` lists the
segments, their duration, and sums those durations up per-day. It shows
we're about an hour too long right now! There are more details of the
segments in `slides.md`, or you can see mostly the same stuff in
`course.py`.

This now contains all of the content from the v1 course, ensuring both
that we've covered everything and that we'll have somewhere to redirect
every page.

Fixes #1082.
Fixes #1465.

---------

Co-authored-by: Nicole LeGare <dlegare.1001@gmail.com>
Co-authored-by: Martin Geisler <mgeisler@google.com>
This commit is contained in:
Dustin J. Mitchell
2023-11-29 10:39:24 -05:00
committed by GitHub
parent ea204774b6
commit 6d19292f16
309 changed files with 6807 additions and 4281 deletions

35
src/modules/exercise.md Normal file
View File

@ -0,0 +1,35 @@
---
minutes: 20
---
# Exercise: Modules for the 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.
If you no longer have your version, that's fine - refer back to the [provided
solution](../methods-and-traits/solution.html).
## Cargo Setup
The Rust playground only supports one file, so you will need to make a Cargo
project on your local filesystem:
```shell
cargo init gui-modules
cd gui-modules
cargo run
```
Edit `src/main.rs` to add `mod` statements, and add additional files in the
`src` directory.
<details>
Encourage students to divide the code in a way that feels natural for them, and
get accustomed to the required `mod`, `use`, and `pub` declarations. Afterward,
discuss what organizations are most idiomatic.
</details>

View File

@ -1,3 +1,7 @@
---
minutes: 5
---
# Filesystem Hierarchy
Omitting the module content will tell Rust to look for it in another file:

36
src/modules/modules.md Normal file
View File

@ -0,0 +1,36 @@
---
minutes: 5
---
# Modules
We have seen how `impl` blocks let us namespace functions to a type.
Similarly, `mod` lets us namespace types and functions:
```rust,editable
mod foo {
pub fn do_something() {
println!("In the foo module");
}
}
mod bar {
pub fn do_something() {
println!("In the bar module");
}
}
fn main() {
foo::do_something();
bar::do_something();
}
```
<details>
* Packages provide functionality and include a `Cargo.toml` file that describes how to build a bundle of 1+ crates.
* Crates are a tree of modules, where a binary crate creates an executable and a library crate compiles to a library.
* Modules define organization, scope, and are the focus of this section.
</details>

View File

@ -1,4 +1,18 @@
# Paths
---
minutes: 10
---
# use, super, self
A module can bring symbols from another module into scope with `use`.
You will typically see something like this at the top of each module:
```rust,editable
use std::collections::HashSet;
use std::process::abort;
```
## Paths
Paths are resolved as follows:
@ -10,10 +24,29 @@ Paths are resolved as follows:
* `crate::foo` refers to `foo` in the root of the current crate,
* `bar::foo` refers to `foo` in the `bar` crate.
A module can bring symbols from another module into scope with `use`.
You will typically see something like this at the top of each module:
<details>
```rust,editable
use std::collections::HashSet;
use std::mem::transmute;
```
* It is common to "re-export" symbols at a shorter path. For example, the
top-level `lib.rs` in a crate might have
```rust,ignore
mod storage;
pub use storage::disk::DiskStorage;
pub use storage::network::NetworkStorage;
```
making `DiskStorage` and `NetworkStorage` available to other crates with a
convenient, short path.
* For the most part, only items that appear in a module need to be `use`'d.
However, a trait must be in scope to call any methods on that trait, even if
a type implementing that trait is already in scope. For example, to use the
`read_to_string` method on a type implementing the `Read` trait, you need to
`use std::io::Read`.
* The `use` statement can have a wildcard: `use std::io::*`. This is
discouraged because it is not clear which items are imported, and those might
change over time.
</details>

185
src/modules/solution.md Normal file
View File

@ -0,0 +1,185 @@
# Solution
<!--
// Copyright 2023 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.
-->
```rust,ignore
// ---- src/widgets.rs ----
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 use button::Button;
pub use label::Label;
pub use window::Window;
```
```rust,ignore
// ---- src/widgets/label.rs ----
use super::Widget;
pub struct Label {
label: String,
}
impl Label {
pub fn new(label: &str) -> Label {
Label {
label: label.to_owned(),
}
}
}
impl Widget for Label {
fn width(&self) -> usize {
// ANCHOR_END: Label-width
self.label
.lines()
.map(|line| line.chars().count())
.max()
.unwrap_or(0)
}
// ANCHOR: Label-draw_into
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
// ANCHOR_END: Label-draw_into
writeln!(buffer, "{}", &self.label).unwrap();
}
}
```
```rust,ignore
// ---- src/widgets/button.rs ----
use super::{Label, Widget};
pub struct Button {
label: Label,
}
impl Button {
pub fn new(label: &str) -> Button {
Button {
label: Label::new(label),
}
}
}
impl Widget for Button {
fn width(&self) -> usize {
// ANCHOR_END: Button-width
self.label.width() + 8 // add a bit of padding
}
// ANCHOR: Button-draw_into
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
// ANCHOR_END: Button-draw_into
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();
}
}
```
```rust,ignore
// ---- src/widgets/window.rs ----
use super::Widget;
pub struct Window {
title: String,
widgets: Vec<Box<dyn Widget>>,
}
impl Window {
pub fn new(title: &str) -> Window {
Window {
title: title.to_owned(),
widgets: Vec::new(),
}
}
pub 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 {
// ANCHOR_END: Window-width
// Add 4 paddings for borders
self.inner_width() + 4
}
// ANCHOR: Window-draw_into
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
// ANCHOR_END: Window-draw_into
let mut inner = String::new();
for widget in &self.widgets {
widget.draw_into(&mut inner);
}
let inner_width = self.inner_width();
// TODO: after learning about error handling, you can 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();
}
}
```
```rust,ignore
// ---- src/main.rs ----
use widgets::Widget;
fn main() {
let mut window = widgets::Window::new("Rust GUI Demo 1.23");
window.add_widget(Box::new(widgets::Label::new(
"This is a small text GUI demo.",
)));
window.add_widget(Box::new(widgets::Button::new("Click me!")));
window.draw();
}
```

View File

@ -1,3 +1,7 @@
---
minutes: 5
---
# Visibility
Modules are a privacy boundary: