You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-15 10:34:18 +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:
committed by
GitHub
parent
ea204774b6
commit
6d19292f16
10
src/methods-and-traits/Cargo.toml
Normal file
10
src/methods-and-traits/Cargo.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "methods-and-traits"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "methods-and-traits"
|
||||
path = "exercise.rs"
|
||||
|
33
src/methods-and-traits/deriving.md
Normal file
33
src/methods-and-traits/deriving.md
Normal file
@ -0,0 +1,33 @@
|
||||
---
|
||||
minutes: 5
|
||||
---
|
||||
|
||||
# Deriving
|
||||
|
||||
Supported traits can be automatically implemented for your custom types, as
|
||||
follows:
|
||||
|
||||
```rust,editable
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Player {
|
||||
name: String,
|
||||
strength: u8,
|
||||
hit_points: u8,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Player::default(); // Default trait adds `default` constructor.
|
||||
let mut p2 = p1.clone(); // Clone trait adds `clone` method.
|
||||
p2.name = String::from("EldurScrollz");
|
||||
// Debug trait adds support for printing with `{:?}`.
|
||||
println!("{:?} vs. {:?}", p1, p2);
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
Derivation is implemented with macros, and many crates provide useful derive
|
||||
macros to add useful functionality. For example, `serde` can derive
|
||||
serialization support for a struct using `#[derive(Serialize)]`.
|
||||
|
||||
</detail>
|
75
src/methods-and-traits/exercise.md
Normal file
75
src/methods-and-traits/exercise.md
Normal file
@ -0,0 +1,75 @@
|
||||
---
|
||||
minutes: 30
|
||||
---
|
||||
|
||||
# Exercise: GUI Library
|
||||
|
||||
Let us design a classical GUI library using our new knowledge of traits and
|
||||
trait objects. We'll only implement the drawing of it (as text) for simplicity.
|
||||
|
||||
We will have a number of widgets in our library:
|
||||
|
||||
* `Window`: has a `title` and contains other widgets.
|
||||
* `Button`: has a `label`. In reality, it would also take a callback
|
||||
function to allow the program to do something when the button is clicked
|
||||
but we won't include that since we're only drawing the GUI.
|
||||
* `Label`: has a `label`.
|
||||
|
||||
The widgets will implement a `Widget` trait, see below.
|
||||
|
||||
Copy the code below to <https://play.rust-lang.org/>, fill in the missing
|
||||
`draw_into` methods so that you implement the `Widget` trait:
|
||||
|
||||
```rust,compile_fail
|
||||
// TODO: remove this when you're done with your implementation.
|
||||
#![allow(unused_imports, unused_variables, dead_code)]
|
||||
|
||||
{{#include exercise.rs:setup}}
|
||||
|
||||
// TODO: Implement `Widget` for `Label`.
|
||||
|
||||
// TODO: Implement `Widget` for `Button`.
|
||||
|
||||
// TODO: Implement `Widget` for `Window`.
|
||||
|
||||
{{#include exercise.rs:main}}
|
||||
```
|
||||
|
||||
The output of the above program can be something simple like this:
|
||||
|
||||
```text
|
||||
========
|
||||
Rust GUI Demo 1.23
|
||||
========
|
||||
|
||||
This is a small text GUI demo.
|
||||
|
||||
| Click me! |
|
||||
```
|
||||
|
||||
If you want to draw aligned text, you can use the
|
||||
[fill/alignment](https://doc.rust-lang.org/std/fmt/index.html#fillalignment)
|
||||
formatting operators. In particular, notice how you can pad with different
|
||||
characters (here a `'/'`) and how you can control alignment:
|
||||
|
||||
```rust,editable
|
||||
fn main() {
|
||||
let width = 10;
|
||||
println!("left aligned: |{:/<width$}|", "foo");
|
||||
println!("centered: |{:/^width$}|", "foo");
|
||||
println!("right aligned: |{:/>width$}|", "foo");
|
||||
}
|
||||
```
|
||||
|
||||
Using such alignment tricks, you can for example produce output like this:
|
||||
|
||||
```text
|
||||
+--------------------------------+
|
||||
| Rust GUI Demo 1.23 |
|
||||
+================================+
|
||||
| This is a small text GUI demo. |
|
||||
| +-----------+ |
|
||||
| | Click me! | |
|
||||
| +-----------+ |
|
||||
+--------------------------------+
|
||||
```
|
148
src/methods-and-traits/exercise.rs
Normal file
148
src/methods-and-traits/exercise.rs
Normal file
@ -0,0 +1,148 @@
|
||||
// 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: solution
|
||||
// ANCHOR: setup
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: setup
|
||||
|
||||
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: 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();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
// ANCHOR: main
|
||||
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();
|
||||
}
|
||||
// ANCHOR_END: main
|
80
src/methods-and-traits/methods.md
Normal file
80
src/methods-and-traits/methods.md
Normal file
@ -0,0 +1,80 @@
|
||||
---
|
||||
minutes: 10
|
||||
---
|
||||
|
||||
# Methods
|
||||
|
||||
Rust allows you to associate functions with your new types. You do this with an
|
||||
`impl` block:
|
||||
|
||||
```rust,editable
|
||||
#[derive(Debug)]
|
||||
struct Race {
|
||||
name: String,
|
||||
laps: Vec<i32>,
|
||||
}
|
||||
|
||||
impl Race {
|
||||
fn new(name: &str) -> Self { // No receiver, a static method
|
||||
Race { name: String::from(name), laps: Vec::new() }
|
||||
}
|
||||
|
||||
fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write access to self
|
||||
self.laps.push(lap);
|
||||
}
|
||||
|
||||
fn print_laps(&self) { // Shared and read-only borrowed access to self
|
||||
println!("Recorded {} laps for {}:", self.laps.len(), self.name);
|
||||
for (idx, lap) in self.laps.iter().enumerate() {
|
||||
println!("Lap {idx}: {lap} sec");
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self) { // Exclusive ownership of self
|
||||
let total = self.laps.iter().sum::<i32>();
|
||||
println!("Race {} is finished, total lap time: {}", self.name, total);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut race = Race::new("Monaco Grand Prix");
|
||||
race.add_lap(70);
|
||||
race.add_lap(68);
|
||||
race.print_laps();
|
||||
race.add_lap(71);
|
||||
race.print_laps();
|
||||
race.finish();
|
||||
// race.add_lap(42);
|
||||
}
|
||||
```
|
||||
|
||||
The `self` arguments specify the "receiver" - the object the method acts on. There
|
||||
are several common receivers for a method:
|
||||
|
||||
* `&self`: borrows the object from the caller using a shared and immutable
|
||||
reference. The object can be used again afterwards.
|
||||
* `&mut self`: borrows the object from the caller using a unique and mutable
|
||||
reference. The object can be used again afterwards.
|
||||
* `self`: takes ownership of the object and moves it away from the caller. The
|
||||
method becomes the owner of the object. The object will be dropped (deallocated)
|
||||
when the method returns, unless its ownership is explicitly
|
||||
transmitted. Complete ownership does not automatically mean mutability.
|
||||
* `mut self`: same as above, but the method can mutate the object.
|
||||
* No receiver: this becomes a static method on the struct. Typically used to
|
||||
create constructors which are called `new` by convention.
|
||||
|
||||
<details>
|
||||
|
||||
Key Points:
|
||||
* It can be helpful to introduce methods by comparing them to functions.
|
||||
* Methods are called on an instance of a type (such as a struct or enum), the first parameter represents the instance as `self`.
|
||||
* Developers may choose to use methods to take advantage of method receiver syntax and to help keep them more organized. By using methods we can keep all the implementation code in one predictable place.
|
||||
* Point out the use of the keyword `self`, a method receiver.
|
||||
* Show that it is an abbreviated term for `self: Self` and perhaps show how the struct name could also be used.
|
||||
* Explain that `Self` is a type alias for the type the `impl` block is in and can be used elsewhere in the block.
|
||||
* Note how `self` is used like other structs and dot notation can be used to refer to individual fields.
|
||||
* This might be a good time to demonstrate how the `&self` differs from `self` by trying to run `finish` twice.
|
||||
* Beyond variants on `self`, there are also [special wrapper types](https://doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be receiver types, such as `Box<Self>`.
|
||||
* Note that references have not been covered yet. References in method receivers are a particularly "natural" form of reference, so there is no need to go into a great level of detail.
|
||||
|
||||
</details>
|
5
src/methods-and-traits/solution.md
Normal file
5
src/methods-and-traits/solution.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Solution
|
||||
|
||||
```rust,editable
|
||||
{{#include exercise.rs:solution}}
|
||||
```
|
93
src/methods-and-traits/trait-objects.md
Normal file
93
src/methods-and-traits/trait-objects.md
Normal file
@ -0,0 +1,93 @@
|
||||
---
|
||||
minutes: 10
|
||||
---
|
||||
|
||||
# Trait Objects
|
||||
|
||||
Trait objects allow for values of different types, for instance in a collection:
|
||||
|
||||
```rust,editable
|
||||
struct Dog { name: String, age: i8 }
|
||||
struct Cat { lives: i8 } // No name needed, cats won't respond anyway.
|
||||
|
||||
trait Pet {
|
||||
fn talk(&self) -> String;
|
||||
}
|
||||
|
||||
impl Pet for Dog {
|
||||
fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) }
|
||||
}
|
||||
|
||||
impl Pet for Cat {
|
||||
fn talk(&self) -> String { String::from("Miau!") }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let pets: Vec<Box<dyn Pet>> = vec![
|
||||
Box::new(Cat { lives: 9 }),
|
||||
Box::new(Dog { name: String::from("Fido"), age: 5 }),
|
||||
];
|
||||
for pet in pets {
|
||||
println!("Hello, who are you? {}", pet.talk());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Memory layout after allocating `pets`:
|
||||
|
||||
```bob
|
||||
Stack Heap
|
||||
.- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - -.
|
||||
: : : :
|
||||
: pets : : +----+----+----+----+ :
|
||||
: +-----------+-------+ : : +-----+-----+ .->| F | i | d | o | :
|
||||
: | ptr | o---+---+-----+-->| o o | o o | | +----+----+----+----+ :
|
||||
: | len | 2 | : : +-|-|-+-|-|-+ `---------. :
|
||||
: | capacity | 2 | : : | | | | data | :
|
||||
: +-----------+-------+ : : | | | | +-------+--|-------+ :
|
||||
: : : | | | '-->| name | o, 4, 4 | :
|
||||
: : : | | | | age | 5 | :
|
||||
`- - - - - - - - - - - - - -' : | | | +-------+----------+ :
|
||||
: | | | :
|
||||
: | | | vtable :
|
||||
: | | | +----------------------+ :
|
||||
: | | '---->| "<Dog as Pet>::talk" | :
|
||||
: | | +----------------------+ :
|
||||
: | | :
|
||||
: | | data :
|
||||
: | | +-------+-------+ :
|
||||
: | '-->| lives | 9 | :
|
||||
: | +-------+-------+ :
|
||||
: | :
|
||||
: | vtable :
|
||||
: | +----------------------+ :
|
||||
: '---->| "<Cat as Pet>::talk" | :
|
||||
: +----------------------+ :
|
||||
: :
|
||||
'- - - - - - - - - - - - - - - - - - - - - - -'
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
- Types that implement a given trait may be of different sizes. This makes it
|
||||
impossible to have things like `Vec<dyn Pet>` in the example above.
|
||||
- `dyn Pet` is a way to tell the compiler about a dynamically sized type that
|
||||
implements `Pet`.
|
||||
- In the example, `pets` is allocated on the stack and the vector data is on the
|
||||
heap. The two vector elements are *fat pointers*:
|
||||
- A fat pointer is a double-width pointer. It has two components: a pointer to
|
||||
the actual object and a pointer to the [virtual method table] (vtable) for the
|
||||
`Pet` implementation of that particular object.
|
||||
- The data for the `Dog` named Fido is the `name` and `age` fields. The `Cat`
|
||||
has a `lives` field.
|
||||
- Compare these outputs in the above example:
|
||||
```rust,ignore
|
||||
println!("{} {}", std::mem::size_of::<Dog>(), std::mem::size_of::<Cat>());
|
||||
println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>());
|
||||
println!("{}", std::mem::size_of::<&dyn Pet>());
|
||||
println!("{}", std::mem::size_of::<Box<dyn Pet>>());
|
||||
```
|
||||
|
||||
[virtual method table]: https://en.wikipedia.org/wiki/Virtual_method_table
|
||||
|
||||
</details>
|
49
src/methods-and-traits/traits.md
Normal file
49
src/methods-and-traits/traits.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
minutes: 10
|
||||
---
|
||||
|
||||
# Traits
|
||||
|
||||
Rust lets you abstract over types with traits. They're similar to interfaces:
|
||||
|
||||
```rust,editable
|
||||
struct Dog { name: String, age: i8 }
|
||||
struct Cat { lives: i8 } // No name needed, cats won't respond anyway.
|
||||
|
||||
trait Pet {
|
||||
fn talk(&self) -> String;
|
||||
|
||||
fn greet(&self) {
|
||||
println!("Oh you're a cutie! What's your name? {}", self.talk());
|
||||
}
|
||||
}
|
||||
|
||||
impl Pet for Dog {
|
||||
fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) }
|
||||
}
|
||||
|
||||
impl Pet for Cat {
|
||||
fn talk(&self) -> String { String::from("Miau!") }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let captain_floof = Cat { lives: 9 };
|
||||
let fido = Dog { name: String::from("Fido"), age: 5 };
|
||||
|
||||
captain_floof.greet();
|
||||
fido.greet();
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
* A trait defines a number of methods that types must have in order to implement
|
||||
the trait.
|
||||
|
||||
* Traits are implemented in an `impl <trait> for <type> { .. }` block.
|
||||
|
||||
* Traits may specify pre-implemented (provided) methods and methods that users
|
||||
are required to implement themselves. Provided methods can rely on required
|
||||
methods. In this case, `greet` is provided, and relies on `talk`.
|
||||
|
||||
</details>
|
Reference in New Issue
Block a user