Skip to content

Commit

Permalink
style: format code blocks
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Mar 18, 2024
1 parent 77b5c49 commit 3c7c0b9
Show file tree
Hide file tree
Showing 104 changed files with 695 additions and 479 deletions.
9 changes: 8 additions & 1 deletion .dprint.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,17 @@
"theme/book.js",
"target/**/*"
],
"exec": {
"commands": [{
"command": "rustfmt --edition 2021",
"exts": ["rs"]
}]
},
"plugins": [
"https://plugins.dprint.dev/markdown-0.16.4.wasm",
"https://plugins.dprint.dev/toml-0.6.1.wasm",
"https://plugins.dprint.dev/json-0.19.2.wasm",
"https://plugins.dprint.dev/typescript-0.89.3.wasm"
"https://plugins.dprint.dev/typescript-0.89.3.wasm",
"https://plugins.dprint.dev/exec-0.4.4.json@c207bf9b9a4ee1f0ecb75c594f774924baf62e8e53a2ce9d873816a408cecbf7"
]
}
9 changes: 9 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,13 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Update rustup
run: rustup self update

- name: Install Rust
run: |
rustup set profile minimal
rustup toolchain install stable -c rustfmt
rustup default stable
- uses: dprint/[email protected]
2 changes: 1 addition & 1 deletion src/conversion/string.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ also allows printing the type as discussed in the section on [`print!`][print].
use std::fmt;
struct Circle {
radius: i32
radius: i32,
}
impl fmt::Display for Circle {
Expand Down
10 changes: 5 additions & 5 deletions src/custom_types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,17 @@ fn inspect(event: WebEvent) {
// Destructure `Click` into `x` and `y`.
WebEvent::Click { x, y } => {
println!("clicked at x={}, y={}.", x, y);
},
}
}
}
fn main() {
let pressed = WebEvent::KeyPress('x');
// `to_owned()` creates an owned `String` from a string slice.
let pasted = WebEvent::Paste("my text".to_owned());
let click = WebEvent::Click { x: 20, y: 80 };
let load = WebEvent::PageLoad;
let unload = WebEvent::PageUnload;
let pasted = WebEvent::Paste("my text".to_owned());
let click = WebEvent::Click { x: 20, y: 80 };
let load = WebEvent::PageLoad;
let unload = WebEvent::PageUnload;
inspect(pressed);
inspect(pasted);
Expand Down
2 changes: 1 addition & 1 deletion src/custom_types/enum/enum_use.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ enum Role {
fn main() {
// Explicitly `use` each name so they are available without
// manual scoping.
use crate::Stage::{Beginner, Advanced};
use crate::Stage::{Advanced, Beginner};
// Automatically `use` each name inside `Role`.
use crate::Role::*;
Expand Down
8 changes: 4 additions & 4 deletions src/custom_types/enum/testcase_linked_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ impl List {
// `self` has type `&List`, and `*self` has type `List`, matching on a
// concrete type `T` is preferred over a match on a reference `&T`
// after Rust 2018 you can use self here and tail (with no ref) below as well,
// rust will infer &s and ref tail.
// rust will infer &s and ref tail.
// See https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/default-match-bindings.html
match *self {
// Can't take ownership of the tail, because `self` is borrowed;
// instead take a reference to the tail
Cons(_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
Nil => 0,
}
}
Expand All @@ -51,10 +51,10 @@ impl List {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
}
Nil => {
format!("Nil")
},
}
}
}
}
Expand Down
15 changes: 12 additions & 3 deletions src/custom_types/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,27 @@ fn main() {
// Make a new point by using struct update syntax to use the fields of our
// other one
let bottom_right = Point { x: 5.2, ..another_point };
let bottom_right = Point {
x: 5.2,
..another_point
};
// `bottom_right.y` will be the same as `point.y` because we used that field
// from `point`
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
// Destructure the point using a `let` binding
let Point { x: left_edge, y: top_edge } = point;
let Point {
x: left_edge,
y: top_edge,
} = point;
let _rectangle = Rectangle {
// struct instantiation is an expression too
top_left: Point { x: left_edge, y: top_edge },
top_left: Point {
x: left_edge,
y: top_edge,
},
bottom_right: bottom_right,
};
Expand Down
10 changes: 2 additions & 8 deletions src/error/iter_result.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ An `Iter::map` operation might fail, for example:
```rust,editable
fn main() {
let strings = vec!["tofu", "93", "18"];
let numbers: Vec<_> = strings
.into_iter()
.map(|s| s.parse::<i32>())
.collect();
let numbers: Vec<_> = strings.into_iter().map(|s| s.parse::<i32>()).collect();
println!("Results: {:?}", numbers);
}
```
Expand Down Expand Up @@ -59,10 +56,7 @@ terminate.
```rust,editable
fn main() {
let strings = vec!["tofu", "93", "18"];
let numbers: Result<Vec<_>, _> = strings
.into_iter()
.map(|s| s.parse::<i32>())
.collect();
let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect();
println!("Results: {:?}", numbers);
}
```
Expand Down
8 changes: 2 additions & 6 deletions src/error/multiple_error_types/option_result.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ other.
use std::num::ParseIntError;
fn double_first(vec: Vec<&str>) -> Option<Result<i32, ParseIntError>> {
vec.first().map(|first| {
first.parse::<i32>().map(|n| 2 * n)
})
vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n))
}
fn main() {
Expand All @@ -35,9 +33,7 @@ of combinators come in handy to swap the `Result` and `Option`.
use std::num::ParseIntError;
fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
let opt = vec.first().map(|first| {
first.parse::<i32>().map(|n| 2 * n)
});
let opt = vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n));
opt.map_or(Ok(None), |r| r.map(Some))
}
Expand Down
2 changes: 1 addition & 1 deletion src/error/multiple_error_types/reenter_question_mark.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn double_first(vec: Vec<&str>) -> Result<i32> {
fn print(result: Result<i32>) {
match result {
Ok(n) => println!("The first doubled is {}", n),
Ok(n) => println!("The first doubled is {}", n),
Err(e) => println!("Error: {}", e),
}
}
Expand Down
12 changes: 5 additions & 7 deletions src/error/multiple_error_types/wrap_error.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ An alternative to boxing errors is to wrap them in your own error type.
```rust,editable
use std::error;
use std::error::Error;
use std::num::ParseIntError;
use std::fmt;
use std::num::ParseIntError;
type Result<T> = std::result::Result<T, DoubleError>;
Expand All @@ -21,12 +21,10 @@ enum DoubleError {
impl fmt::Display for DoubleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DoubleError::EmptyVec =>
write!(f, "please use a vector with at least one element"),
DoubleError::EmptyVec => write!(f, "please use a vector with at least one element"),
// The wrapped error contains additional information and is available
// via the source() method.
DoubleError::Parse(..) =>
write!(f, "the provided string could not be parsed as int"),
DoubleError::Parse(..) => write!(f, "the provided string could not be parsed as int"),
}
}
}
Expand Down Expand Up @@ -63,13 +61,13 @@ fn double_first(vec: Vec<&str>) -> Result<i32> {
fn print(result: Result<i32>) {
match result {
Ok(n) => println!("The first doubled is {}", n),
Ok(n) => println!("The first doubled is {}", n),
Err(e) => {
println!("Error: {}", e);
if let Some(source) = e.source() {
println!(" Caused by: {}", source);
}
},
}
}
}
Expand Down
12 changes: 7 additions & 5 deletions src/error/option_unwrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ fn give_adult(drink: Option<&str>) {
// Specify a course of action for each case.
match drink {
Some("lemonade") => println!("Yuck! Too sugary."),
Some(inner) => println!("{}? How nice.", inner),
None => println!("No drink? Oh well."),
Some(inner) => println!("{}? How nice.", inner),
None => println!("No drink? Oh well."),
}
}
Expand All @@ -40,15 +40,17 @@ fn give_adult(drink: Option<&str>) {
fn drink(drink: Option<&str>) {
// `unwrap` returns a `panic` when it receives a `None`.
let inside = drink.unwrap();
if inside == "lemonade" { panic!("AAAaaaaa!!!!"); }
if inside == "lemonade" {
panic!("AAAaaaaa!!!!");
}
println!("I love {}s!!!!!", inside);
}
fn main() {
let water = Some("water");
let water = Some("water");
let lemonade = Some("lemonade");
let void = None;
let void = None;
give_adult(water);
give_adult(lemonade);
Expand Down
22 changes: 16 additions & 6 deletions src/error/option_unwrap/and_then.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,40 @@ which is an invalid type for `eat()`.
```rust,editable
#![allow(dead_code)]
#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }
#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }
#[derive(Debug)]
enum Food {
CordonBleu,
Steak,
Sushi,
}
#[derive(Debug)]
enum Day {
Monday,
Tuesday,
Wednesday,
}
// We don't have the ingredients to make Sushi.
fn have_ingredients(food: Food) -> Option<Food> {
match food {
Food::Sushi => None,
_ => Some(food),
_ => Some(food),
}
}
// We have the recipe for everything except Cordon Bleu.
fn have_recipe(food: Food) -> Option<Food> {
match food {
Food::CordonBleu => None,
_ => Some(food),
_ => Some(food),
}
}
// To make a dish, we need both the recipe and the ingredients.
// We can represent the logic with a chain of `match`es:
fn cookable_v1(food: Food) -> Option<Food> {
match have_recipe(food) {
None => None,
None => None,
Some(food) => have_ingredients(food),
}
}
Expand All @@ -58,7 +68,7 @@ fn cookable_v2(food: Food) -> Option<Food> {
fn eat(food: Food, day: Day) {
match cookable_v3(food) {
Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
None => println!("Oh no. We don't get to eat on {:?}?", day),
None => println!("Oh no. We don't get to eat on {:?}?", day),
}
}
Expand Down
Loading

0 comments on commit 3c7c0b9

Please sign in to comment.