1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-13 17:44:20 +02:00

Format all Markdown files with dprint (#1157)

This is the result of running `dprint fmt` after removing `src/` from
the list of excluded directories.

This also reformats the Rust code: we might want to tweak this a bit in
the future since some of the changes removes the hand-formatting. Of
course, this formatting can be seen as a mis-feature, so maybe this is
good overall.

Thanks to mdbook-i18n-helpers 0.2, the POT file is nearly unchanged
after this, meaning that all existing translations remain valid! A few
messages were changed because of stray whitespace characters:

     msgid ""
     "Slices always borrow from another object. In this example, `a` has to remain "
    -"'alive' (in scope) for at least as long as our slice. "
    +"'alive' (in scope) for at least as long as our slice."
     msgstr ""

The formatting is enforced in CI and we will have to see how annoying
this is in practice for the many contributors. If it becomes annoying,
we should look into fixing dprint/check#11 so that `dprint` can annotate
the lines that need fixing directly, then I think we can consider more
strict formatting checks.

I added more customization to `rustfmt.toml`. This is to better emulate
the dense style used in the course:

- `max_width = 85` allows lines to take up the full width available in
our code blocks (when taking margins and the line numbers into account).
- `wrap_comments = true` ensures that we don't show very long comments
in the code examples. I edited some comments to shorten them and avoid
unnecessary line breaks — please trim other unnecessarily long comments
when you see them! Remember we're writing code for slides 😄
- `use_small_heuristics = "Max"` allows for things like struct literals
and if-statements to take up the full line width configured above.

The formatting settings apply to all our Rust code right now — I think
we could improve this with https://github.com/dprint/dprint/issues/711
which lets us add per-directory `dprint` configuration files. However,
the `inherit: true` setting is not yet implemented (as far as I can
tell), so a nested configuration file will have to copy most or all of
the top-level file.
This commit is contained in:
Martin Geisler
2023-12-31 00:15:07 +01:00
committed by GitHub
parent f43e72e0ad
commit c9f66fd425
302 changed files with 3067 additions and 2622 deletions

View File

@ -7,4 +7,3 @@ publish = false
[[bin]]
name = "methods-and-traits"
path = "exercise.rs"

View File

@ -17,7 +17,7 @@ struct Player {
fn main() {
let p1 = Player::default(); // Default trait adds `default` constructor.
let mut p2 = p1.clone(); // Clone trait adds `clone` method.
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);

View File

@ -9,11 +9,11 @@ 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`.
- `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.

View File

@ -35,9 +35,7 @@ pub struct Label {
impl Label {
fn new(label: &str) -> Label {
Label {
label: label.to_owned(),
}
Label { label: label.to_owned() }
}
}
@ -47,9 +45,7 @@ pub struct Button {
impl Button {
fn new(label: &str) -> Button {
Button {
label: Label::new(label),
}
Button { label: Label::new(label) }
}
}
@ -60,10 +56,7 @@ pub struct Window {
impl Window {
fn new(title: &str) -> Window {
Window {
title: title.to_owned(),
widgets: Vec::new(),
}
Window { title: title.to_owned(), widgets: Vec::new() }
}
fn add_widget(&mut self, widget: Box<dyn Widget>) {
@ -126,11 +119,7 @@ impl Widget for Button {
impl Widget for Label {
fn width(&self) -> usize {
self.label
.lines()
.map(|line| line.chars().count())
.max()
.unwrap_or(0)
self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0)
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {

View File

@ -15,22 +15,26 @@ struct Race {
}
impl Race {
fn new(name: &str) -> Self { // No receiver, a static method
// No receiver, a static method
fn new(name: &str) -> Self {
Self { name: String::from(name), laps: Vec::new() }
}
fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write access to self
// Exclusive borrowed read-write access to self
fn add_lap(&mut self, lap: i32) {
self.laps.push(lap);
}
fn print_laps(&self) { // Shared and read-only borrowed access to self
// Shared and read-only borrowed access to self
fn print_laps(&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
// Exclusive ownership of self
fn finish(self) {
let total: i32 = self.laps.iter().sum();
println!("Race {} is finished, total lap time: {}", self.name, total);
}
@ -48,32 +52,42 @@ fn main() {
}
```
The `self` arguments specify the "receiver" - the object the method acts on. There
are several common receivers for a method:
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
- `&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
- `&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
- `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
- `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>`.
- 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>`.
</details>

View File

@ -7,19 +7,28 @@ minutes: 10
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.
struct Dog {
name: String,
age: i8,
}
struct Cat {
lives: i8,
}
trait Pet {
fn talk(&self) -> String;
}
impl Pet for Dog {
fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) }
fn talk(&self) -> String {
format!("Woof, my name is {}!", self.name)
}
}
impl Pet for Cat {
fn talk(&self) -> String { String::from("Miau!") }
fn talk(&self) -> String {
String::from("Miau!")
}
}
fn main() {
@ -74,19 +83,19 @@ Memory layout after allocating `pets`:
- `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*:
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 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>>());
```
```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

View File

@ -7,8 +7,13 @@ minutes: 10
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.
struct Dog {
name: String,
age: i8,
}
struct Cat {
lives: i8,
}
trait Pet {
fn talk(&self) -> String;
@ -19,11 +24,15 @@ trait Pet {
}
impl Pet for Dog {
fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) }
fn talk(&self) -> String {
format!("Woof, my name is {}!", self.name)
}
}
impl Pet for Cat {
fn talk(&self) -> String { String::from("Miau!") }
fn talk(&self) -> String {
String::from("Miau!")
}
}
fn main() {
@ -37,12 +46,12 @@ fn main() {
<details>
* A trait defines a number of methods that types must have in order to implement
- 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 are implemented in an `impl <trait> for <type> { .. }` block.
* Traits may specify pre-implemented (provided) methods and methods that users
- 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`.