major update prepared for ch17

This commit is contained in:
KaiserY 2024-10-20 23:44:05 +08:00
parent e675c74913
commit a6dff2e316
795 changed files with 81953 additions and 1039 deletions

View File

@ -4,7 +4,7 @@
## 状态 ## 状态
施工完毕。 - 新增 ch17 async & await 施工中
PS: PS:

View File

@ -1,11 +1,19 @@
[book] [book]
title = "Rust 程序设计语言 简体中文版" title = "Rust 程序设计语言 简体中文版"
authors = ["Steve Klabnik 和 Carol Nichols以及来自 Rust 社区的贡献Rust 中文社区翻译)"] authors = [
description = "Rust 程序设计语言 简体中文版" "Steve Klabnik",
language = "zh-CN" "Carol Nichols",
"Chris Krycho",
"来自 Rust 社区的贡献Rust 中文社区翻译)",
]
[output.html] [output.html]
additional-css = ["ferris.css", "theme/2018-edition.css"] additional-css = [
"ferris.css",
"theme/2018-edition.css",
"theme/semantic-notes.css",
"theme/listing.css",
]
additional-js = ["ferris.js"] additional-js = ["ferris.js"]
git-repository-url = "https://github.com/KaiserY/trpl-zh-cn/tree/main" git-repository-url = "https://github.com/KaiserY/trpl-zh-cn/tree/main"
edit-url-template = "https://github.com/KaiserY/trpl-zh-cn/edit/main/{path}" edit-url-template = "https://github.com/KaiserY/trpl-zh-cn/edit/main/{path}"
@ -13,3 +21,6 @@ edit-url-template = "https://github.com/KaiserY/trpl-zh-cn/edit/main/{path}"
[output.typst-pdf] [output.typst-pdf]
pdf = true pdf = true
section-number = true section-number = true
[rust]
edition = "2021"

View File

@ -1,4 +1,10 @@
$ cargo build $ cargo build
Downloading crates ...
Downloaded rand_core v0.6.2
Downloaded getrandom v0.2.2
Downloaded rand_chacha v0.3.0
Downloaded ppv-lite86 v0.2.10
Downloaded libc v0.2.86
Compiling libc v0.2.86 Compiling libc v0.2.86
Compiling getrandom v0.2.2 Compiling getrandom v0.2.2
Compiling cfg-if v1.0.0 Compiling cfg-if v1.0.0
@ -18,7 +24,7 @@ error[E0308]: mismatched types
= note: expected reference `&String` = note: expected reference `&String`
found reference `&{integer}` found reference `&{integer}`
note: method defined here note: method defined here
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/cmp.rs:836:8 --> /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/cmp.rs:839:8
For more information about this error, try `rustc --explain E0308`. For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` (bin "guessing_game") due to 1 previous error error: could not compile `guessing_game` (bin "guessing_game") due to 1 previous error

View File

@ -4,13 +4,15 @@ error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5 --> src/main.rs:4:5
| |
2 | let x = 5; 2 | let x = 5;
| - | - first assignment to `x`
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
3 | println!("The value of x is: {x}"); 3 | println!("The value of x is: {x}");
4 | x = 6; 4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable | ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0384`. For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` (bin "variables") due to 1 previous error error: could not compile `variables` (bin "variables") due to 1 previous error

View File

@ -14,10 +14,10 @@ fn main() {
// 没有特殊之处 // 没有特殊之处
fn takes_ownership(some_string: String) { // some_string 进入作用域 fn takes_ownership(some_string: String) { // some_string 进入作用域
println!("{}", some_string); println!("{some_string}");
} // 这里some_string 移出作用域并调用 `drop` 方法。 } // 这里some_string 移出作用域并调用 `drop` 方法。
// 占用的内存被释放 // 占用的内存被释放
fn makes_copy(some_integer: i32) { // some_integer 进入作用域 fn makes_copy(some_integer: i32) { // some_integer 进入作用域
println!("{}", some_integer); println!("{some_integer}");
} // 这里some_integer 移出作用域。没有特殊之处 } // 这里some_integer 移出作用域。没有特殊之处

View File

@ -3,7 +3,7 @@ fn main() {
let (s2, len) = calculate_length(s1); let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len); println!("The length of '{s2}' is {len}.");
} }
fn calculate_length(s: String) -> (String, usize) { fn calculate_length(s: String) -> (String, usize) {

View File

@ -4,6 +4,6 @@ fn main() {
s.push_str(", world!"); // push_str() 在字符串后追加字面值 s.push_str(", world!"); // push_str() 在字符串后追加字面值
println!("{}", s); // 将打印 `hello, world!` println!("{s}"); // 将打印 `hello, world!`
// ANCHOR_END: here // ANCHOR_END: here
} }

View File

@ -0,0 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "ownership"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "ownership"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,8 @@
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
s = String::from("ahoy");
println!("{s}, world!");
// ANCHOR_END: here
}

View File

@ -3,7 +3,7 @@ fn main() {
let len = calculate_length(&s1); let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len); println!("The length of '{s1}' is {len}.");
} }
// ANCHOR: here // ANCHOR: here

View File

@ -4,10 +4,10 @@ fn main() {
let r1 = &s; // 没问题 let r1 = &s; // 没问题
let r2 = &s; // 没问题 let r2 = &s; // 没问题
println!("{} and {}", r1, r2); println!("{r1} and {r2}");
// 此位置之后 r1 和 r2 不再使用 // 此位置之后 r1 和 r2 不再使用
let r3 = &mut s; // 没问题 let r3 = &mut s; // 没问题
println!("{}", r3); println!("{r3}");
// ANCHOR_END: here // ANCHOR_END: here
} }

View File

@ -18,6 +18,6 @@ fn main() {
s.clear(); // 错误! s.clear(); // 错误!
println!("the first word is: {}", word); println!("the first word is: {word}");
} }
// ANCHOR_END: here // ANCHOR_END: here

View File

@ -8,10 +8,10 @@ error[E0277]: cannot add `Option<i8>` to `i8`
| |
= help: the trait `Add<Option<i8>>` is not implemented for `i8` = help: the trait `Add<Option<i8>>` is not implemented for `i8`
= help: the following other types implement trait `Add<Rhs>`: = help: the following other types implement trait `Add<Rhs>`:
<i8 as Add> `&'a i8` implements `Add<i8>`
<i8 as Add<&i8>> `&i8` implements `Add<&i8>`
<&'a i8 as Add<i8>> `i8` implements `Add<&i8>`
<&i8 as Add<&i8>> `i8` implements `Add`
For more information about this error, try `rustc --explain E0277`. For more information about this error, try `rustc --explain E0277`.
error: could not compile `enums` (bin "enums") due to 1 previous error error: could not compile `enums` (bin "enums") due to 1 previous error

View File

@ -7,8 +7,8 @@ error[E0004]: non-exhaustive patterns: `None` not covered
| ^ pattern `None` not covered | ^ pattern `None` not covered
| |
note: `Option<i32>` defined here note: `Option<i32>` defined here
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/option.rs:572:1 --> /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/option.rs:574:1
::: /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/core/src/option.rs:576:5 ::: /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/core/src/option.rs:578:5
| |
= note: not covered = note: not covered
= note: the matched value is of type `Option<i32>` = note: the matched value is of type `Option<i32>`

View File

@ -9,6 +9,14 @@ error[E0277]: the `?` operator can only be used in a function that returns `Resu
| ^ cannot use the `?` operator in a function that returns `()` | ^ cannot use the `?` operator in a function that returns `()`
| |
= help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()` = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`
help: consider adding return type
|
3 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
4 | let greeting_file = File::open("hello.txt")?;
5 +
6 + Ok(())
7 + }
|
For more information about this error, try `rustc --explain E0277`. For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` (bin "error-handling") due to 1 previous error error: could not compile `error-handling` (bin "error-handling") due to 1 previous error

View File

@ -12,23 +12,5 @@ help: consider introducing a named lifetime parameter
9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { 9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++ | ++++ ++ ++ ++
error: lifetime may not live long enough
--> src/main.rs:11:9
|
9 | fn longest(x: &str, y: &str) -> &str {
| - let's call the lifetime of this reference `'1`
10 | if x.len() > y.len() {
11 | x
| ^ returning this value requires that `'1` must outlive `'static`
error: lifetime may not live long enough
--> src/main.rs:13:9
|
9 | fn longest(x: &str, y: &str) -> &str {
| - let's call the lifetime of this reference `'2`
...
13 | y
| ^ returning this value requires that `'2` must outlive `'static`
For more information about this error, try `rustc --explain E0106`. For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` (bin "chapter10") due to 3 previous errors error: could not compile `chapter10` (bin "chapter10") due to 1 previous error

View File

@ -1,4 +1,3 @@
// ANCHOR: here
pub fn add(left: usize, right: usize) -> usize { pub fn add(left: usize, right: usize) -> usize {
left + right left + right
} }
@ -18,4 +17,3 @@ mod tests {
panic!("Make this test fail"); panic!("Make this test fail");
} }
} }
// ANCHOR_END: here

View File

@ -1,4 +1,3 @@
// ANCHOR: here
#[derive(Debug)] #[derive(Debug)]
struct Rectangle { struct Rectangle {
width: u32, width: u32,
@ -10,4 +9,3 @@ impl Rectangle {
self.width > other.width && self.height > other.height self.width > other.width && self.height > other.height
} }
} }
// ANCHOR_END: here

View File

@ -1,4 +1,4 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
a + 2 a + 2
} }
@ -8,6 +8,7 @@ mod tests {
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
assert_eq!(4, add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }
} }

View File

@ -13,8 +13,8 @@ failures:
I got the value 8 I got the value 8
thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9: thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9:
assertion `left == right` failed assertion `left == right` failed
left: 5 left: 10
right: 10 right: 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

View File

@ -10,12 +10,12 @@ mod tests {
#[test] #[test]
fn this_test_will_pass() { fn this_test_will_pass() {
let value = prints_and_returns_10(4); let value = prints_and_returns_10(4);
assert_eq!(10, value); assert_eq!(value, 10);
} }
#[test] #[test]
fn this_test_will_fail() { fn this_test_will_fail() {
let value = prints_and_returns_10(8); let value = prints_and_returns_10(8);
assert_eq!(5, value); assert_eq!(value, 5);
} }
} }

View File

@ -1,4 +1,4 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
a + 2 a + 2
} }
@ -8,16 +8,19 @@ mod tests {
#[test] #[test]
fn add_two_and_two() { fn add_two_and_two() {
assert_eq!(4, add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }
#[test] #[test]
fn add_three_and_two() { fn add_three_and_two() {
assert_eq!(5, add_two(3)); let result = add_two(3);
assert_eq!(result, 5);
} }
#[test] #[test]
fn one_hundred() { fn one_hundred() {
assert_eq!(102, add_two(100)); let result = add_two(100);
assert_eq!(result, 102);
} }
} }

View File

@ -1,9 +1,9 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
internal_adder(a, 2) internal_adder(a, 2)
} }
fn internal_adder(a: i32, b: i32) -> i32 { fn internal_adder(left: usize, right: usize) -> usize {
a + b left + right
} }
#[cfg(test)] #[cfg(test)]
@ -12,6 +12,7 @@ mod tests {
#[test] #[test]
fn internal() { fn internal() {
assert_eq!(4, internal_adder(2, 2)); let result = internal_adder(2, 2);
assert_eq!(result, 4);
} }
} }

View File

@ -1,9 +1,9 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
internal_adder(a, 2) internal_adder(a, 2)
} }
fn internal_adder(a: i32, b: i32) -> i32 { fn internal_adder(left: usize, right: usize) -> usize {
a + b left + right
} }
#[cfg(test)] #[cfg(test)]
@ -12,6 +12,7 @@ mod tests {
#[test] #[test]
fn internal() { fn internal() {
assert_eq!(4, internal_adder(2, 2)); let result = internal_adder(2, 2);
assert_eq!(result, 4);
} }
} }

View File

@ -2,5 +2,6 @@ use adder::add_two;
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
assert_eq!(4, add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }

View File

@ -9,10 +9,10 @@ test tests::it_adds_two ... FAILED
failures: failures:
---- tests::it_adds_two stdout ---- ---- tests::it_adds_two stdout ----
thread 'tests::it_adds_two' panicked at src/lib.rs:11:9: thread 'tests::it_adds_two' panicked at src/lib.rs:12:9:
assertion `left == right` failed assertion `left == right` failed
left: 4 left: 5
right: 5 right: 4
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

View File

@ -1,5 +1,5 @@
// ANCHOR: here // ANCHOR: here
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
a + 3 a + 3
} }
// ANCHOR_END: here // ANCHOR_END: here
@ -10,6 +10,7 @@ mod tests {
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
assert_eq!(4, add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }
} }

View File

@ -12,8 +12,7 @@ mod tests {
let result = greeting("Carol"); let result = greeting("Carol");
assert!( assert!(
result.contains("Carol"), result.contains("Carol"),
"Greeting did not contain name, value was `{}`", "Greeting did not contain name, value was `{result}`"
result
); );
} }
// ANCHOR_END: here // ANCHOR_END: here

View File

@ -4,8 +4,8 @@ $ cargo test
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests running 2 tests
test expensive_test ... ignored test tests::expensive_test ... ignored
test it_works ... ok test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s

View File

@ -1,10 +1,22 @@
#[test] pub fn add(left: usize, right: usize) -> usize {
fn it_works() { left + right
assert_eq!(2 + 2, 4);
} }
#[test] // ANCHOR: here
#[ignore] #[cfg(test)]
fn expensive_test() { mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
#[test]
#[ignore]
fn expensive_test() {
// 需要运行一个小时的代码 // 需要运行一个小时的代码
}
} }
// ANCHOR_END: here

View File

@ -1,9 +1,9 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
internal_adder(a, 2) internal_adder(a, 2)
} }
fn internal_adder(a: i32, b: i32) -> i32 { fn internal_adder(left: usize, right: usize) -> usize {
a + b left + right
} }
#[cfg(test)] #[cfg(test)]
@ -12,6 +12,7 @@ mod tests {
#[test] #[test]
fn internal() { fn internal() {
assert_eq!(4, internal_adder(2, 2)); let result = internal_adder(2, 2);
assert_eq!(result, 4);
} }
} }

View File

@ -1,6 +1,7 @@
use adder; use adder::add_two;
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
assert_eq!(4, adder::add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }

View File

@ -1,9 +1,9 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
internal_adder(a, 2) internal_adder(a, 2)
} }
fn internal_adder(a: i32, b: i32) -> i32 { fn internal_adder(left: usize, right: usize) -> usize {
a + b left + right
} }
#[cfg(test)] #[cfg(test)]
@ -12,6 +12,7 @@ mod tests {
#[test] #[test]
fn internal() { fn internal() {
assert_eq!(4, internal_adder(2, 2)); let result = internal_adder(2, 2);
assert_eq!(result, 4);
} }
} }

View File

@ -1,9 +1,11 @@
use adder; use adder::add_two;
mod common; mod common;
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
common::setup(); common::setup();
assert_eq!(4, adder::add_two(2));
let result = add_two(2);
assert_eq!(result, 4);
} }

View File

@ -22,8 +22,8 @@ failures:
I got the value 8 I got the value 8
thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9: thread 'tests::this_test_will_fail' panicked at src/lib.rs:19:9:
assertion `left == right` failed assertion `left == right` failed
left: 5 left: 10
right: 10 right: 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

View File

@ -10,12 +10,12 @@ mod tests {
#[test] #[test]
fn this_test_will_pass() { fn this_test_will_pass() {
let value = prints_and_returns_10(4); let value = prints_and_returns_10(4);
assert_eq!(10, value); assert_eq!(value, 10);
} }
#[test] #[test]
fn this_test_will_fail() { fn this_test_will_fail() {
let value = prints_and_returns_10(8); let value = prints_and_returns_10(8);
assert_eq!(5, value); assert_eq!(value, 5);
} }
} }

View File

@ -1,9 +1,9 @@
pub fn add_two(a: i32) -> i32 { pub fn add_two(a: usize) -> usize {
internal_adder(a, 2) internal_adder(a, 2)
} }
fn internal_adder(a: i32, b: i32) -> i32 { fn internal_adder(left: usize, right: usize) -> usize {
a + b left + right
} }
#[cfg(test)] #[cfg(test)]
@ -12,6 +12,7 @@ mod tests {
#[test] #[test]
fn internal() { fn internal() {
assert_eq!(4, internal_adder(2, 2)); let result = internal_adder(2, 2);
assert_eq!(result, 4);
} }
} }

View File

@ -1,6 +1,7 @@
use adder; use adder::add_two;
#[test] #[test]
fn it_adds_two() { fn it_adds_two() {
assert_eq!(4, adder::add_two(2)); let result = add_two(2);
assert_eq!(result, 4);
} }

View File

@ -1,4 +1,6 @@
$ cargo run $ cargo run
Locking 1 package to latest compatible version
Adding closure-example v0.1.0 (/Users/chris/dev/rust-lang/book/tmp/listings/ch13-functional-features/listing-13-04)
Compiling closure-example v0.1.0 (file:///projects/closure-example) Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example` Running `target/debug/closure-example`

View File

@ -1,4 +1,6 @@
$ cargo run $ cargo run
Locking 1 package to latest compatible version
Adding closure-example v0.1.0 (/Users/chris/dev/rust-lang/book/tmp/listings/ch13-functional-features/listing-13-05)
Compiling closure-example v0.1.0 (file:///projects/closure-example) Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example` Running `target/debug/closure-example`

View File

@ -10,6 +10,11 @@ error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` clos
| --- captured by this `FnMut` closure | --- captured by this `FnMut` closure
18 | sort_operations.push(value); 18 | sort_operations.push(value);
| ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait | ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait
|
help: consider cloning the value if the performance cost is acceptable
|
18 | sort_operations.push(value.clone());
| ++++++++
For more information about this error, try `rustc --explain E0507`. For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error error: could not compile `rectangles` (bin "rectangles") due to 1 previous error

View File

@ -0,0 +1,8 @@
[package]
name = "add_one"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -6,10 +6,14 @@ error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `
58 | self.sent_messages.push(String::from(message)); 58 | self.sent_messages.push(String::from(message));
| ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable | ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
| |
help: consider changing this to be a mutable reference help: consider changing this to be a mutable reference in the `impl` method and the `trait` definition
|
2 ~ fn send(&mut self, msg: &str);
3 | }
...
56 | impl Messenger for MockMessenger {
57 ~ fn send(&mut self, message: &str) {
| |
2 | fn send(&mut self, msg: &str);
| ~~~~~~~~~
For more information about this error, try `rustc --explain E0596`. For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` (lib test) due to 1 previous error error: could not compile `limit-tracker` (lib test) due to 1 previous error

View File

@ -11,10 +11,6 @@ error[E0382]: borrow of moved value: `val`
| ^^^^^ value borrowed here after move | ^^^^^ value borrowed here after move
| |
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
9 | tx.send(val.clone()).unwrap();
| ++++++++
For more information about this error, try `rustc --explain E0382`. For more information about this error, try `rustc --explain E0382`.
error: could not compile `message-passing` (bin "message-passing") due to 1 previous error error: could not compile `message-passing` (bin "message-passing") due to 1 previous error

View File

@ -6,11 +6,21 @@ error[E0382]: borrow of moved value: `counter`
5 | let counter = Mutex::new(0); 5 | let counter = Mutex::new(0);
| ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait | ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait
... ...
8 | for _ in 0..10 {
| -------------- inside of this loop
9 | let handle = thread::spawn(move || { 9 | let handle = thread::spawn(move || {
| ------- value moved into closure here, in previous iteration of loop | ------- value moved into closure here, in previous iteration of loop
... ...
21 | println!("Result: {}", *counter.lock().unwrap()); 21 | println!("Result: {}", *counter.lock().unwrap());
| ^^^^^^^ value borrowed here after move | ^^^^^^^ value borrowed here after move
|
help: consider moving the expression out of the loop so it is only moved once
|
8 ~ let mut value = counter.lock();
9 ~ for _ in 0..10 {
10 | let handle = thread::spawn(move || {
11 ~ let mut num = value.unwrap();
|
For more information about this error, try `rustc --explain E0382`. For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error error: could not compile `shared-state` (bin "shared-state") due to 1 previous error

View File

@ -22,7 +22,7 @@ note: required because it's used within this closure
11 | let handle = thread::spawn(move || { 11 | let handle = thread::spawn(move || {
| ^^^^^^^ | ^^^^^^^
note: required by a bound in `spawn` note: required by a bound in `spawn`
--> /rustc/9b00956e56009bab2aa15d7bff10916599e3d6d6/library/std/src/thread/mod.rs:677:1 --> /rustc/eeb90cda1969383f56a2637cbd3037bdf598841c/library/std/src/thread/mod.rs:688:1
For more information about this error, try `rustc --explain E0277`. For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error error: could not compile `shared-state` (bin "shared-state") due to 1 previous error

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,17 @@
extern crate trpl; // required for mdbook test
fn main() {
// TODO: we'll add this next!
}
// ANCHOR: all
use trpl::Html;
async fn page_title(url: &str) -> Option<String> {
let response = trpl::get(url).await;
let response_text = response.text().await;
Html::parse(&response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}
// ANCHOR_END: all

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,16 @@
extern crate trpl; // required for mdbook test
use trpl::Html;
fn main() {
// TODO: we'll add this next!
}
async fn page_title(url: &str) -> Option<String> {
// ANCHOR: chaining
let response_text = trpl::get(url).await.text().await;
// ANCHOR_END: chaining
Html::parse(&response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,21 @@
extern crate trpl; // required for mdbook test
use trpl::Html;
// ANCHOR: main
async fn main() {
let args: Vec<String> = std::env::args().collect();
let url = &args[1];
match page_title(url).await {
Some(title) => println!("The title for {url} was {title}"),
None => println!("{url} had no title"),
}
}
// ANCHOR_END: main
async fn page_title(url: &str) -> Option<String> {
let response_text = trpl::get(url).await.text().await;
Html::parse(&response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,3 @@
$ cargo run "http://www.rust-lang.org"
The title for http://www.rust-lang.org was
Rust Programming Language

View File

@ -0,0 +1,24 @@
extern crate trpl; // required for mdbook test
use trpl::Html;
// ANCHOR: run
fn main() {
let args: Vec<String> = std::env::args().collect();
trpl::run(async {
let url = &args[1];
match page_title(url).await {
Some(title) => println!("The title for {url} was {title}"),
None => println!("{url} had no title"),
}
})
}
// ANCHOR_END: run
async fn page_title(url: &str) -> Option<String> {
let response_text = trpl::get(url).await.text().await;
Html::parse(&response_text)
.select_first("title")
.map(|title_element| title_element.inner_html())
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,34 @@
extern crate trpl; // required for mdbook test
// ANCHOR: all
use trpl::{Either, Html};
fn main() {
let args: Vec<String> = std::env::args().collect();
trpl::run(async {
let title_fut_1 = page_title(&args[1]);
let title_fut_2 = page_title(&args[2]);
let (url, maybe_title) =
match trpl::race(title_fut_1, title_fut_2).await {
Either::Left(left) => left,
Either::Right(right) => right,
};
println!("{url} returned first");
match maybe_title {
Some(title) => println!("Its page title is: '{title}'"),
None => println!("Its title could not be parsed."),
}
})
}
async fn page_title(url: &str) -> (&str, Option<String>) {
let text = trpl::get(url).await.text().await;
let title = Html::parse(&text)
.select_first("title")
.map(|title| title.inner_html());
(url, title)
}
// ANCHOR_END: all

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,21 @@
extern crate trpl; // required for mdbook test
// ANCHOR: all
use std::time::Duration;
fn main() {
trpl::run(async {
trpl::spawn_task(async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
}
// ANCHOR_END: all

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,23 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
// ANCHOR: handle
let handle = trpl::spawn_task(async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
});
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
handle.await.unwrap();
// ANCHOR_END: handle
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,25 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
// ANCHOR: join
let fut1 = async {
for i in 1..10 {
println!("hi number {i} from the first task!");
trpl::sleep(Duration::from_millis(500)).await;
}
};
let fut2 = async {
for i in 1..5 {
println!("hi number {i} from the second task!");
trpl::sleep(Duration::from_millis(500)).await;
}
};
trpl::join(fut1, fut2).await;
// ANCHOR_END: join
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,15 @@
extern crate trpl; // required for mdbook test
fn main() {
trpl::run(async {
// ANCHOR: channel
let (tx, mut rx) = trpl::channel();
let val = String::from("hi");
tx.send(val).unwrap();
let received = rx.recv().await.unwrap();
println!("Got: {received}");
// ANCHOR_END: channel
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,27 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
// ANCHOR: many-messages
let (tx, mut rx) = trpl::channel();
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
// ANCHOR_END: many-messages
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,33 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
let (tx, mut rx) = trpl::channel();
// ANCHOR: futures
let tx_fut = async {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
trpl::join(tx_fut, rx_fut).await;
// ANCHOR_END: futures
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,33 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
// ANCHOR: with-move
let (tx, mut rx) = trpl::channel();
let tx_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
eprintln!("received '{value}'");
}
};
trpl::join(tx_fut, rx_fut).await;
// ANCHOR_END: with-move
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,48 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
// ANCHOR: here
let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_millis(500)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_millis(1500)).await;
}
};
trpl::join3(tx1_fut, tx_fut, rx_fut).await;
// ANCHOR_END: here
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,48 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
// ANCHOR: here
trpl::join!(tx1_fut, tx_fut, rx_fut);
// ANCHOR_END: here
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,50 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
// ANCHOR: here
let futures = vec![tx1_fut, rx_fut, tx_fut];
trpl::join_all(futures).await;
// ANCHOR_END: here
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1,51 @@
extern crate trpl; // required for mdbook test
use std::time::Duration;
fn main() {
trpl::run(async {
let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
// ANCHOR: here
let futures =
vec![Box::new(tx1_fut), Box::new(rx_fut), Box::new(tx_fut)];
trpl::join_all(futures).await;
// ANCHOR_END: here
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
[package]
name = "async_await"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
trpl = { path = "../../../packages/trpl" }

View File

@ -0,0 +1 @@
$

View File

@ -0,0 +1,51 @@
extern crate trpl; // required for mdbook test
use std::{future::Future, time::Duration};
fn main() {
trpl::run(async {
let (tx, mut rx) = trpl::channel();
let tx1 = tx.clone();
let tx1_fut = async move {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("future"),
];
for val in vals {
tx1.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
let rx_fut = async {
while let Some(value) = rx.recv().await {
println!("received '{value}'");
}
};
let tx_fut = async move {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
trpl::sleep(Duration::from_secs(1)).await;
}
};
// ANCHOR: here
let futures: Vec<Box<dyn Future<Output = ()>>> =
vec![Box::new(tx1_fut), Box::new(rx_fut), Box::new(tx_fut)];
// ANCHOR_END: here
trpl::join_all(futures).await;
});
}

Some files were not shown because too many files have changed in this diff Show More