1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-16 14:17:34 +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 = "binary-tree"
path = "exercise.rs"

View File

@ -4,7 +4,8 @@ minutes: 10
# `Box<T>`
[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned pointer to data on the heap:
[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned pointer
to data on the heap:
```rust,editable
fn main() {
@ -13,7 +14,6 @@ fn main() {
}
```
```bob
Stack Heap
.- - - - - - -. .- - - - - - -.
@ -27,7 +27,8 @@ fn main() {
`- - - - - - -' `- - - - - - -'
```
`Box<T>` implements `Deref<Target = T>`, which means that you can [call methods
`Box<T>` implements `Deref<Target = T>`, which means that you can
[call methods
from `T` directly on a `Box<T>`](https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-deref-coercion).
Recursive data types or data types with dynamic sizes need to use a `Box`:
@ -35,14 +36,15 @@ Recursive data types or data types with dynamic sizes need to use a `Box`:
```rust,editable
#[derive(Debug)]
enum List<T> {
/// A non-empty list, consisting of the first element and the rest of the list.
/// A non-empty list: first element and the rest of the list.
Element(T, Box<List<T>>),
/// An empty list.
Nil,
}
fn main() {
let list: List<i32> = List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
let list: List<i32> =
List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
println!("{list:?}");
}
```
@ -59,20 +61,28 @@ fn main() {
: : : :
'- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - - - - - - - - - - - - -'
```
<details>
* `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not null.
* A `Box` can be useful when you:
* have a type whose size that can't be known at compile time, but the Rust compiler wants to know an exact size.
* want to transfer ownership of a large amount of data. To avoid copying large amounts of data on the stack, instead store the data on the heap in a `Box` so only the pointer is moved.
- `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not
null.
- A `Box` can be useful when you:
- have a type whose size that can't be known at compile time, but the Rust
compiler wants to know an exact size.
- want to transfer ownership of a large amount of data. To avoid copying large
amounts of data on the stack, instead store the data on the heap in a `Box`
so only the pointer is moved.
* If `Box` was not used and we attempted to embed a `List` directly into the `List`,
the compiler would not compute a fixed size of the struct in memory (`List` would be of infinite size).
- If `Box` was not used and we attempted to embed a `List` directly into the
`List`, the compiler would not compute a fixed size of the struct in memory
(`List` would be of infinite size).
* `Box` solves this problem as it has the same size as a regular pointer and just points at the next
element of the `List` in the heap.
- `Box` solves this problem as it has the same size as a regular pointer and
just points at the next element of the `List` in the heap.
* Remove the `Box` in the List definition and show the compiler error. "Recursive with indirection" is a hint you might want to use a Box or reference of some kind, instead of storing a value directly.
- Remove the `Box` in the List definition and show the compiler error.
"Recursive with indirection" is a hint you might want to use a Box or
reference of some kind, instead of storing a value directly.
# More to Explore
@ -86,7 +96,8 @@ enum List<T> {
}
fn main() {
let list: List<i32> = List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
let list: List<i32> =
List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
println!("{list:?}");
}
```

View File

@ -39,9 +39,7 @@ pub struct BinaryTree<T: Ord> {
impl<T: Ord> BinaryTree<T> {
fn new() -> Self {
Self {
root: Subtree::new(),
}
Self { root: Subtree::new() }
}
fn insert(&mut self, value: T) {
@ -94,11 +92,7 @@ impl<T: Ord> Subtree<T> {
impl<T: Ord> Node<T> {
fn new(value: T) -> Self {
Self {
value,
left: Subtree::new(),
right: Subtree::new(),
}
Self { value, left: Subtree::new(), right: Subtree::new() }
}
}
@ -131,7 +125,8 @@ mod tests {
fn has() {
let mut tree = BinaryTree::new();
fn check_has(tree: &BinaryTree<i32>, exp: &[bool]) {
let got: Vec<bool> = (0..exp.len()).map(|i| tree.has(&(i as i32))).collect();
let got: Vec<bool> =
(0..exp.len()).map(|i| tree.has(&(i as i32))).collect();
assert_eq!(&got, exp);
}

View File

@ -19,9 +19,9 @@ fn main() {
}
```
* See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context.
* You can *downgrade* a shared pointer into a [`Weak`][4] pointer to create cycles
that will get dropped.
- See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context.
- You can _downgrade_ a shared pointer into a [`Weak`][4] pointer to create
cycles that will get dropped.
[1]: https://doc.rust-lang.org/std/rc/struct.Rc.html
[2]: ../concurrency/shared_state/arc.md
@ -30,13 +30,16 @@ fn main() {
<details>
* `Rc`'s count ensures that its contained value is valid for as long as there are references.
* `Rc` in Rust is like `std::shared_ptr` in C++.
* `Rc::clone` is cheap: it creates a pointer to the same allocation and increases the reference count. Does not make a deep clone and can generally be ignored when looking for performance issues in code.
* `make_mut` actually clones the inner value if necessary ("clone-on-write") and returns a mutable reference.
* Use `Rc::strong_count` to check the reference count.
* `Rc::downgrade` gives you a *weakly reference-counted* object to
create cycles that will be dropped properly (likely in combination with
`RefCell`).
- `Rc`'s count ensures that its contained value is valid for as long as there
are references.
- `Rc` in Rust is like `std::shared_ptr` in C++.
- `Rc::clone` is cheap: it creates a pointer to the same allocation and
increases the reference count. Does not make a deep clone and can generally be
ignored when looking for performance issues in code.
- `make_mut` actually clones the inner value if necessary ("clone-on-write") and
returns a mutable reference.
- Use `Rc::strong_count` to check the reference count.
- `Rc::downgrade` gives you a _weakly reference-counted_ object to create cycles
that will be dropped properly (likely in combination with `RefCell`).
</details>