From 5363f350887b1e5b5dd21a86f88c8af9d7fea6da Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:18:25 +0200 Subject: Merging upstream version 1.67.1+dfsg1. Signed-off-by: Daniel Baumann --- src/doc/book/.github/ISSUE_TEMPLATE/bug_report.md | 8 +- src/doc/book/.github/workflows/main.yml | 8 +- src/doc/book/README.md | 2 +- .../listing-02-04/output.txt | 5 +- .../output.txt | 10 +- .../output-only-01-no-type-annotations/output.txt | 7 +- .../no-listing-04-cant-use-after-move/output.txt | 4 +- .../output.txt | 2 +- .../output.txt | 2 +- .../no-listing-14-dangling-reference/output.txt | 2 +- .../no-listing-19-slice-error/output.txt | 4 +- .../listing-05-02/src/main.rs | 4 +- .../listing-05-03/src/main.rs | 4 +- .../listing-05-04/src/main.rs | 4 +- .../listing-05-05/src/main.rs | 4 +- .../listing-05-11/output.txt | 2 +- .../output-only-01-debug/output.txt | 2 +- .../no-listing-10-non-exhaustive-match/output.txt | 20 +-- .../listing-08-06/output.txt | 8 +- .../output-only-01-not-char-boundary/output.txt | 2 +- .../ch09-error-handling/listing-09-10/output.txt | 9 +- .../listing-10-16/output.txt | 2 +- .../listing-11-03/output.txt | 2 +- .../listing-11-10/output.txt | 2 +- .../no-listing-03-introducing-a-bug/output.txt | 2 +- .../no-listing-04-bug-in-add-two/output.txt | 2 +- .../no-listing-06-greeter-with-bug/output.txt | 2 +- .../output.txt | 2 +- .../no-listing-08-guess-with-bug/output.txt | 2 +- .../output.txt | 2 +- .../output-only-01-show-output/output.txt | 2 +- .../ch12-an-io-project/listing-12-16/output.txt | 2 +- .../listing-13-03/output.txt | 13 +- .../listing-13-08/output.txt | 17 +- .../ch15-smart-pointers/listing-15-03/output.txt | 14 +- .../ch15-smart-pointers/listing-15-23/output.txt | 2 +- .../listing-16-09/output.txt | 2 +- .../listing-16-14/output.txt | 34 ++-- .../output-only-01-move-drop/output.txt | 2 +- .../listings/ch17-oop/listing-17-10/output.txt | 2 +- .../listing-18-08/output.txt | 22 +-- .../listing-18-15/src/main.rs | 10 +- .../listing-18-16/src/main.rs | 6 +- .../listing-19-20/output.txt | 14 +- .../no-listing-18-returns-closure/output.txt | 2 +- .../ch20-web-server/listing-20-22/output.txt | 14 +- .../output.txt | 6 + src/doc/book/rust-toolchain | 2 +- src/doc/book/src/ch05-00-structs.md | 2 +- src/doc/book/src/ch05-01-defining-structs.md | 76 ++++++--- src/doc/book/src/ch05-02-example-structs.md | 34 ++-- src/doc/book/src/ch05-03-method-syntax.md | 102 ++++++----- src/doc/book/src/ch06-00-enums.md | 4 +- src/doc/book/src/ch06-01-defining-an-enum.md | 58 +++---- src/doc/book/src/ch06-02-match.md | 80 ++++----- src/doc/book/src/ch06-03-if-let.md | 14 +- src/doc/book/src/title-page.md | 2 +- src/doc/embedded-book/src/intro/install/linux.md | 5 +- src/doc/embedded-book/src/intro/no-std.md | 4 +- .../embedded-book/src/peripherals/singletons.md | 2 +- src/doc/embedded-book/src/start/hardware.md | 2 +- src/doc/nomicon/src/lifetime-mismatch.md | 2 +- src/doc/nomicon/src/unchecked-uninit.md | 13 +- src/doc/nomicon/src/vec/vec-alloc.md | 1 - src/doc/nomicon/src/vec/vec-final.md | 2 - src/doc/nomicon/src/vec/vec-insert-remove.md | 16 +- src/doc/nomicon/src/vec/vec-into-iter.md | 14 +- src/doc/nomicon/src/vec/vec-layout.md | 19 +-- src/doc/nomicon/src/vec/vec-raw.md | 2 - src/doc/nomicon/src/vec/vec-zsts.md | 5 +- src/doc/reference/src/attributes.md | 2 + src/doc/reference/src/attributes/codegen.md | 23 +++ .../reference/src/behavior-considered-undefined.md | 18 +- src/doc/reference/src/comments.md | 2 +- src/doc/reference/src/expressions/literal-expr.md | 18 +- src/doc/reference/src/items/extern-crates.md | 7 +- src/doc/reference/src/items/external-blocks.md | 17 ++ src/doc/reference/src/items/generics.md | 2 +- src/doc/reference/src/macros-by-example.md | 2 + src/doc/reference/src/special-types-and-traits.md | 2 +- src/doc/reference/src/tokens.md | 147 +++++++--------- src/doc/reference/src/trait-bounds.md | 2 +- src/doc/rust-by-example/.github/workflows/rbe.yml | 2 +- src/doc/rust-by-example/src/crates/using_lib.md | 2 +- src/doc/rust-by-example/src/fn/closures.md | 22 +-- .../src/fn/closures/input_parameters.md | 2 +- src/doc/rust-by-example/src/hello/print.md | 2 +- src/doc/rust-by-example/src/scope/lifetime.md | 2 +- .../src/std_misc/file/read_lines.md | 34 ++++ src/doc/rust-by-example/src/types/cast.md | 20 +-- src/doc/rust-by-example/triagebot.toml | 3 + src/doc/rustc-dev-guide/src/asm.md | 44 ++--- src/doc/rustc-dev-guide/src/backend/monomorph.md | 2 +- .../rustc-dev-guide/src/backend/updating-llvm.md | 188 ++++++++++----------- src/doc/rustc-dev-guide/src/bug-fix-procedure.md | 8 +- .../src/building/how-to-build-and-run.md | 4 +- src/doc/rustc-dev-guide/src/building/suggested.md | 11 +- src/doc/rustc-dev-guide/src/closure.md | 4 +- src/doc/rustc-dev-guide/src/compiler-team.md | 14 +- src/doc/rustc-dev-guide/src/constants.md | 2 +- src/doc/rustc-dev-guide/src/contributing.md | 18 +- src/doc/rustc-dev-guide/src/conventions.md | 2 +- .../src/diagnostics/diagnostic-structs.md | 20 ++- .../rustc-dev-guide/src/diagnostics/lintstore.md | 5 - src/doc/rustc-dev-guide/src/getting-started.md | 2 +- src/doc/rustc-dev-guide/src/macro-expansion.md | 84 ++++----- src/doc/rustc-dev-guide/src/mir/dataflow.md | 2 +- .../rustc-dev-guide/src/mir/drop-elaboration.md | 2 +- src/doc/rustc-dev-guide/src/overview.md | 2 +- src/doc/rustc-dev-guide/src/parallel-rustc.md | 4 +- src/doc/rustc-dev-guide/src/part-5-intro.md | 6 +- .../queries/incremental-compilation-in-detail.md | 10 +- src/doc/rustc-dev-guide/src/query.md | 81 ++------- src/doc/rustc-dev-guide/src/rustdoc-internals.md | 2 +- src/doc/rustc-dev-guide/src/salsa.md | 2 +- src/doc/rustc-dev-guide/src/stability.md | 10 +- src/doc/rustc-dev-guide/src/tests/ui.md | 4 + src/doc/rustc-dev-guide/src/traits/resolution.md | 2 +- .../rustc-dev-guide/src/traits/specialization.md | 2 +- src/doc/rustc-dev-guide/src/ty-fold.md | 2 +- src/doc/rustc-dev-guide/src/type-inference.md | 30 ++-- src/doc/rustc/src/SUMMARY.md | 2 + src/doc/rustc/src/codegen-options/index.md | 10 +- src/doc/rustc/src/command-line-arguments.md | 27 +++ src/doc/rustc/src/linker-plugin-lto.md | 94 ++++++----- src/doc/rustc/src/platform-support.md | 11 +- src/doc/rustc/src/platform-support/fuchsia.md | 113 ++++++++++++- .../rustc/src/platform-support/mipsel-sony-psx.md | 49 ++++++ src/doc/rustc/src/platform-support/nto-qnx.md | 118 +++++++++++++ src/doc/rustc/src/platform-support/unknown-uefi.md | 38 +---- src/doc/rustc/src/target-tier-policy.md | 27 +++ src/doc/rustdoc/book.toml | 4 + src/doc/rustdoc/src/lints.md | 2 +- src/doc/style-guide/src/principles.md | 4 +- .../src/language-features/abi-efiapi.md | 23 +++ .../extended-varargs-abi-support.md | 10 ++ .../native-link-modifiers-verbatim.md | 20 --- 137 files changed, 1306 insertions(+), 902 deletions(-) create mode 100644 src/doc/rustc/src/platform-support/mipsel-sony-psx.md create mode 100644 src/doc/rustc/src/platform-support/nto-qnx.md create mode 100644 src/doc/unstable-book/src/language-features/abi-efiapi.md create mode 100644 src/doc/unstable-book/src/language-features/extended-varargs-abi-support.md delete mode 100644 src/doc/unstable-book/src/language-features/native-link-modifiers-verbatim.md (limited to 'src/doc') diff --git a/src/doc/book/.github/ISSUE_TEMPLATE/bug_report.md b/src/doc/book/.github/ISSUE_TEMPLATE/bug_report.md index c1157112f..2423c4cd4 100644 --- a/src/doc/book/.github/ISSUE_TEMPLATE/bug_report.md +++ b/src/doc/book/.github/ISSUE_TEMPLATE/bug_report.md @@ -3,8 +3,12 @@ name: Bug report about: Create a report to help us improve --- -- [ ] I have checked the latest `main` branch to see if this has already been fixed -- [ ] I have searched existing issues and pull requests for duplicates +- I have searched open and closed issues and pull requests for duplicates, using these search terms: + - + - + - +- I have checked the latest `main` branch to see if this has already been fixed, in this file: + - URL to the section(s) of the book with this problem: diff --git a/src/doc/book/.github/workflows/main.yml b/src/doc/book/.github/workflows/main.yml index d5b3249be..64ab49c51 100644 --- a/src/doc/book/.github/workflows/main.yml +++ b/src/doc/book/.github/workflows/main.yml @@ -12,12 +12,12 @@ jobs: - name: Install Rust run: | rustup set profile minimal - rustup toolchain install 1.62 -c rust-docs - rustup default 1.62 + rustup toolchain install 1.65 -c rust-docs + rustup default 1.65 - name: Install mdbook run: | mkdir bin - curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.14/mdbook-v0.4.14-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin + curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.21/mdbook-v0.4.21-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin echo "$(pwd)/bin" >> ${GITHUB_PATH} - name: Report versions run: | @@ -41,7 +41,7 @@ jobs: - name: Install mdbook run: | mkdir bin - curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.14/mdbook-v0.4.14-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin + curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.21/mdbook-v0.4.21-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin echo "$(pwd)/bin" >> ${GITHUB_PATH} - name: Install aspell run: sudo apt-get install aspell diff --git a/src/doc/book/README.md b/src/doc/book/README.md index 91c64ce25..94e1a004a 100644 --- a/src/doc/book/README.md +++ b/src/doc/book/README.md @@ -30,7 +30,7 @@ rust-lang/rust uses in [this file][rust-mdbook]. To get it: [rust-mdbook]: https://github.com/rust-lang/rust/blob/master/src/tools/rustbook/Cargo.toml ```bash -$ cargo install mdbook --vers [version-num] +$ cargo install mdbook --version ``` ## Building diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt index fbc0cec33..70a0c930c 100644 --- a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt @@ -11,10 +11,13 @@ error[E0308]: mismatched types --> src/main.rs:22:21 | 22 | match guess.cmp(&secret_number) { - | ^^^^^^^^^^^^^^ expected struct `String`, found integer + | --- ^^^^^^^^^^^^^^ expected struct `String`, found integer + | | + | arguments to this function are incorrect | = note: expected reference `&String` found reference `&{integer}` +note: associated function defined here For more information about this error, try `rustc --explain E0308`. error: could not compile `guessing_game` due to previous error diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt index a5a85f4f6..6ae56e09d 100644 --- a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt @@ -1,5 +1,11 @@ $ cargo run Compiling functions v0.1.0 (file:///projects/functions) +error: expected expression, found `let` statement + --> src/main.rs:2:14 + | +2 | let x = (let y = 6); + | ^^^ + error: expected expression, found statement (`let`) --> src/main.rs:2:14 | @@ -27,8 +33,8 @@ help: remove these parentheses | 2 - let x = (let y = 6); 2 + let x = let y = 6; - | + | For more information about this error, try `rustc --explain E0658`. warning: `functions` (bin "functions") generated 1 warning -error: could not compile `functions` due to 2 previous errors; 1 warning emitted +error: could not compile `functions` due to 3 previous errors; 1 warning emitted diff --git a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt index d9807cee0..8a11cccd5 100644 --- a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt +++ b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt @@ -4,7 +4,12 @@ error[E0282]: type annotations needed --> src/main.rs:2:9 | 2 | let guess = "42".parse().expect("Not a number!"); - | ^^^^^ consider giving `guess` a type + | ^^^^^ + | +help: consider giving `guess` an explicit type + | +2 | let guess: _ = "42".parse().expect("Not a number!"); + | +++ For more information about this error, try `rustc --explain E0282`. error: could not compile `no_type_annotations` due to previous error diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt index 6435eeb44..05987f7c8 100644 --- a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt @@ -7,11 +7,11 @@ error[E0382]: borrow of moved value: `s1` | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait 3 | let s2 = s1; | -- value moved here -4 | +4 | 5 | println!("{}, world!", s1); | ^^ value borrowed here after move | - = note: this error originates in the macro `$crate::format_args_nl` (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) For more information about this error, try `rustc --explain E0382`. error: could not compile `ownership` due to previous error diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt index 71c29f68f..8820d2d69 100644 --- a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt @@ -7,7 +7,7 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time | ------ first mutable borrow occurs here 5 | let r2 = &mut s; | ^^^^^^ second mutable borrow occurs here -6 | +6 | 7 | println!("{}, {}", r1, r2); | -- first borrow later used here diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt index df94c30e9..d1e9db2c4 100644 --- a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt @@ -8,7 +8,7 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta 5 | let r2 = &s; // no problem 6 | let r3 = &mut s; // BIG PROBLEM | ^^^^^^ mutable borrow occurs here -7 | +7 | 8 | println!("{}, {}, and {}", r1, r2, r3); | -- immutable borrow later used here diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt index fddca683b..b466a3dce 100644 --- a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt @@ -10,7 +10,7 @@ error[E0106]: missing lifetime specifier help: consider using the `'static` lifetime | 5 | fn dangle() -> &'static String { - | ~~~~~~~~ + | +++++++ For more information about this error, try `rustc --explain E0106`. error: could not compile `ownership` due to previous error diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt index 62dc4ad52..ab0c41f4d 100644 --- a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt @@ -5,10 +5,10 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta | 16 | let word = first_word(&s); | -- immutable borrow occurs here -17 | +17 | 18 | s.clear(); // error! | ^^^^^^^^^ mutable borrow occurs here -19 | +19 | 20 | println!("the first word is: {}", word); | ---- immutable borrow later used here diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs index e0f7a6cd3..122d25164 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs @@ -8,9 +8,9 @@ struct User { // ANCHOR: here fn main() { let user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), active: true, + username: String::from("someusername123"), + email: String::from("someone@example.com"), sign_in_count: 1, }; } diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs index 7a078e7e8..35eea8a9a 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs @@ -8,9 +8,9 @@ struct User { // ANCHOR: here fn main() { let mut user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), active: true, + username: String::from("someusername123"), + email: String::from("someone@example.com"), sign_in_count: 1, }; diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs index aa7823af4..8614561c1 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs @@ -8,9 +8,9 @@ struct User { // ANCHOR: here fn build_user(email: String, username: String) -> User { User { - email: email, - username: username, active: true, + username: username, + email: email, sign_in_count: 1, } } diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs index 8d84a3060..c893c86a9 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs @@ -8,9 +8,9 @@ struct User { // ANCHOR: here fn build_user(email: String, username: String) -> User { User { - email, - username, active: true, + username, + email, sign_in_count: 1, } } diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt index b761fccd6..7d3bfcdac 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt @@ -8,7 +8,7 @@ error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` | = help: the trait `std::fmt::Display` is not implemented for `Rectangle` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead - = note: this error originates in the macro `$crate::format_args_nl` (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) For more information about this error, try `rustc --explain E0277`. error: could not compile `rectangles` due to previous error diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt index 69c8b38a6..58cb842bf 100644 --- a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt @@ -8,7 +8,7 @@ error[E0277]: `Rectangle` doesn't implement `Debug` | = help: the trait `Debug` is not implemented for `Rectangle` = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle` - = note: this error originates in the macro `$crate::format_args_nl` (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 annotating `Rectangle` with `#[derive(Debug)]` | 1 | #[derive(Debug)] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt index c5a6c51bb..bec72849a 100644 --- a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt @@ -1,18 +1,18 @@ $ cargo run Compiling enums v0.1.0 (file:///projects/enums) error[E0004]: non-exhaustive patterns: `None` not covered - --> src/main.rs:3:15 - | -3 | match x { - | ^ pattern `None` not covered - | + --> src/main.rs:3:15 + | +3 | match x { + | ^ pattern `None` not covered + | note: `Option` defined here - = note: the matched value is of type `Option` + = note: the matched value is of type `Option` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown - | -4 ~ Some(i) => Some(i + 1), -5 ~ None => todo!(), - | + | +4 ~ Some(i) => Some(i + 1), +5 ~ None => todo!(), + | For more information about this error, try `rustc --explain E0004`. error: could not compile `enums` due to previous error diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-06/output.txt b/src/doc/book/listings/ch08-common-collections/listing-08-06/output.txt index ab512a9e6..3104205f3 100644 --- a/src/doc/book/listings/ch08-common-collections/listing-08-06/output.txt +++ b/src/doc/book/listings/ch08-common-collections/listing-08-06/output.txt @@ -5,12 +5,12 @@ error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immuta | 4 | let first = &v[0]; | - immutable borrow occurs here -5 | +5 | 6 | v.push(6); | ^^^^^^^^^ mutable borrow occurs here -7 | -8 | println!("The first element is: {}", first); - | ----- immutable borrow later used here +7 | +8 | println!("The first element is: {first}"); + | ----- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. error: could not compile `collections` due to previous error diff --git a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt index 98d1f183a..35db879c9 100644 --- a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt +++ b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt @@ -2,5 +2,5 @@ $ cargo run Compiling collections v0.1.0 (file:///projects/collections) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/collections` -thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', library/core/src/str/mod.rs:127:5 +thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/main.rs:4:14 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-10/output.txt b/src/doc/book/listings/ch09-error-handling/listing-09-10/output.txt index 26e4ff8cc..75b9cf2e3 100644 --- a/src/doc/book/listings/ch09-error-handling/listing-09-10/output.txt +++ b/src/doc/book/listings/ch09-error-handling/listing-09-10/output.txt @@ -3,11 +3,10 @@ $ cargo run error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) --> src/main.rs:4:48 | -3 | / fn main() { -4 | | let greeting_file = File::open("hello.txt")?; - | | ^ cannot use the `?` operator in a function that returns `()` -5 | | } - | |_- this function should return `Result` or `Option` to accept `?` +3 | fn main() { + | --------- this function should return `Result` or `Option` to accept `?` +4 | let greeting_file = File::open("hello.txt")?; + | ^ cannot use the `?` operator in a function that returns `()` | = help: the trait `FromResidual>` is not implemented for `()` diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/output.txt index b63bf83a1..ad7327209 100644 --- a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/output.txt +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/output.txt @@ -7,7 +7,7 @@ error[E0597]: `x` does not live long enough | ^^ borrowed value does not live long enough 7 | } | - `x` dropped here while still borrowed -8 | +8 | 9 | println!("r: {}", r); | - borrow later used here diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt index 0c2fd0327..2fa5cf077 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt @@ -19,4 +19,4 @@ failures: test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt index 0512cd59f..681cfbb81 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt @@ -22,4 +22,4 @@ failures: test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt index fdeb597e3..7c62822f7 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt @@ -19,4 +19,4 @@ failures: test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt index 0af0401e3..28e2414be 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt @@ -20,4 +20,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt index 3049543a7..3366e3ace 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt @@ -18,4 +18,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt index d2ba1961b..cebebdaee 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt @@ -18,4 +18,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt index f59dddec4..9318d4ce0 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt @@ -16,4 +16,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt index c8cba98fe..c176e88b8 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt @@ -20,4 +20,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt index 8caaeda06..4ececf245 100644 --- a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt @@ -31,4 +31,4 @@ failures: test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt index d0cda6024..3c34e3945 100644 --- a/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt @@ -20,4 +20,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-03/output.txt b/src/doc/book/listings/ch13-functional-features/listing-13-03/output.txt index 37d83618a..68838deff 100644 --- a/src/doc/book/listings/ch13-functional-features/listing-13-03/output.txt +++ b/src/doc/book/listings/ch13-functional-features/listing-13-03/output.txt @@ -4,9 +4,16 @@ error[E0308]: mismatched types --> src/main.rs:5:29 | 5 | let n = example_closure(5); - | ^- help: try using a conversion method: `.to_string()` - | | - | expected struct `String`, found integer + | --------------- ^- help: try using a conversion method: `.to_string()` + | | | + | | expected struct `String`, found integer + | arguments to this function are incorrect + | +note: closure parameter defined here + --> src/main.rs:2:28 + | +2 | let example_closure = |x| x; + | ^ For more information about this error, try `rustc --explain E0308`. error: could not compile `closure-example` due to previous error diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt b/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt index 7a39ac618..a91053766 100644 --- a/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt +++ b/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt @@ -3,16 +3,13 @@ $ cargo run error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure --> src/main.rs:18:30 | -15 | let value = String::from("by key called"); - | ----- captured outer variable -16 | -17 | list.sort_by_key(|r| { - | ______________________- -18 | | sort_operations.push(value); - | | ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait -19 | | r.width -20 | | }); - | |_____- captured by this `FnMut` closure +15 | let value = String::from("by key called"); + | ----- captured outer variable +16 | +17 | list.sort_by_key(|r| { + | --- captured by this `FnMut` closure +18 | sort_operations.push(value); + | ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait For more information about this error, try `rustc --explain E0507`. error: could not compile `rectangles` due to previous error diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt index 437d74b5c..d5522cd53 100644 --- a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt @@ -13,15 +13,5 @@ help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` repre 2 | Cons(i32, Box), | ++++ + -error[E0391]: cycle detected when computing drop-check constraints for `List` - --> src/main.rs:1:1 - | -1 | enum List { - | ^^^^^^^^^ - | - = note: ...which immediately requires computing drop-check constraints for `List` again - = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst }, value: List } }` - -Some errors have detailed explanations: E0072, E0391. -For more information about an error, try `rustc --explain E0072`. -error: could not compile `cons-list` due to 2 previous errors +For more information about this error, try `rustc --explain E0072`. +error: could not compile `cons-list` due to previous error diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt index c44e69f13..3749c845c 100644 --- a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt @@ -18,4 +18,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s -error: test failed, to rerun pass '--lib' +error: test failed, to rerun pass `--lib` diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt index 0795a3a4f..db8518537 100644 --- a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt @@ -10,7 +10,7 @@ error[E0382]: borrow of moved value: `val` 10 | println!("val is {}", val); | ^^^ value borrowed here after move | - = note: this error originates in the macro `$crate::format_args_nl` (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) For more information about this error, try `rustc --explain E0382`. error: could not compile `message-passing` due to previous error diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt index 9546e1e48..0634b86e5 100644 --- a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt @@ -1,20 +1,26 @@ $ cargo run Compiling shared-state v0.1.0 (file:///projects/shared-state) error[E0277]: `Rc>` cannot be sent between threads safely - --> src/main.rs:11:22 - | -11 | let handle = thread::spawn(move || { - | ______________________^^^^^^^^^^^^^_- - | | | - | | `Rc>` cannot be sent between threads safely -12 | | let mut num = counter.lock().unwrap(); -13 | | -14 | | *num += 1; -15 | | }); - | |_________- within this `[closure@src/main.rs:11:36: 15:10]` - | - = help: within `[closure@src/main.rs:11:36: 15:10]`, the trait `Send` is not implemented for `Rc>` - = note: required because it appears within the type `[closure@src/main.rs:11:36: 15:10]` + --> src/main.rs:11:36 + | +11 | let handle = thread::spawn(move || { + | ------------- ^------ + | | | + | ______________________|_____________within this `[closure@src/main.rs:11:36: 11:43]` + | | | + | | required by a bound introduced by this call +12 | | let mut num = counter.lock().unwrap(); +13 | | +14 | | *num += 1; +15 | | }); + | |_________^ `Rc>` cannot be sent between threads safely + | + = help: within `[closure@src/main.rs:11:36: 11:43]`, the trait `Send` is not implemented for `Rc>` +note: required because it's used within this closure + --> src/main.rs:11:36 + | +11 | let handle = thread::spawn(move || { + | ^^^^^^^ note: required by a bound in `spawn` For more information about this error, try `rustc --explain E0277`. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt index f7be53b9a..301a9a44a 100644 --- a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt +++ b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt @@ -5,7 +5,7 @@ error[E0382]: use of moved value: `v` | 4 | let v = vec![1, 2, 3]; | - move occurs because `v` has type `Vec`, which does not implement the `Copy` trait -5 | +5 | 6 | let handle = thread::spawn(move || { | ------- value moved into closure here 7 | println!("Here's a vector: {:?}", v); diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/output.txt b/src/doc/book/listings/ch17-oop/listing-17-10/output.txt index 74330fa0a..e0a455f3b 100644 --- a/src/doc/book/listings/ch17-oop/listing-17-10/output.txt +++ b/src/doc/book/listings/ch17-oop/listing-17-10/output.txt @@ -7,7 +7,7 @@ error[E0277]: the trait bound `String: Draw` is not satisfied | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String` | = help: the trait `Draw` is implemented for `Button` - = note: required for the cast to the object type `dyn Draw` + = note: required for the cast from `String` to the object type `dyn Draw` For more information about this error, try `rustc --explain E0277`. error: could not compile `gui` due to previous error diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt index 72274d07c..0fd5373b8 100644 --- a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt @@ -1,19 +1,19 @@ $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) error[E0005]: refutable pattern in local binding: `None` not covered - --> src/main.rs:3:9 - | -3 | let Some(x) = some_option_value; - | ^^^^^^^ pattern `None` not covered - | - = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant - = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html + --> src/main.rs:3:9 + | +3 | let Some(x) = some_option_value; + | ^^^^^^^ pattern `None` not covered + | + = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant + = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html note: `Option` defined here - = note: the matched value is of type `Option` + = note: the matched value is of type `Option` help: you might want to use `if let` to ignore the variant that isn't matched - | -3 | let x = if let Some(x) = some_option_value { x } else { todo!() }; - | ++++++++++ ++++++++++++++++++++++ + | +3 | let x = if let Some(x) = some_option_value { x } else { todo!() }; + | ++++++++++ ++++++++++++++++++++++ For more information about this error, try `rustc --explain E0005`. error: could not compile `patterns` due to previous error diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs index 4ddef0aaf..a3138b227 100644 --- a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs @@ -13,15 +13,13 @@ fn main() { println!("The Quit variant has no data to destructure."); } Message::Move { x, y } => { - println!( - "Move in the x direction {x} and in the y direction {y}" - ); + println!("Move in the x direction {x} and in the y direction {y}"); } Message::Write(text) => { println!("Text message: {text}"); } - Message::ChangeColor(r, g, b) => println!( - "Change the color to red {r}, green {g}, and blue {b}", - ), + Message::ChangeColor(r, g, b) => { + println!("Change the color to red {r}, green {g}, and blue {b}",) + } } } diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs index 4c958601b..1e7ad5f19 100644 --- a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs @@ -17,9 +17,9 @@ fn main() { Message::ChangeColor(Color::Rgb(r, g, b)) => { println!("Change color to red {r}, green {g}, and blue {b}"); } - Message::ChangeColor(Color::Hsv(h, s, v)) => println!( - "Change color to hue {h}, saturation {s}, value {v}" - ), + Message::ChangeColor(Color::Hsv(h, s, v)) => { + println!("Change color to hue {h}, saturation {s}, value {v}") + } _ => (), } } diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt index 684508245..a3b281e3f 100644 --- a/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt @@ -1,12 +1,18 @@ $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) -error[E0283]: type annotations needed +error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type --> src/main.rs:20:43 | +2 | fn baby_name() -> String; + | ------------------------- `Animal::baby_name` defined here +... 20 | println!("A baby dog is called a {}", Animal::baby_name()); - | ^^^^^^^^^^^^^^^^^ cannot infer type + | ^^^^^^^^^^^^^^^^^ cannot call associated function of trait | - = note: cannot satisfy `_: Animal` +help: use the fully-qualified path to the only available implementation + | +20 | println!("A baby dog is called a {}", <::Dog as Animal>::baby_name()); + | +++++++++ + -For more information about this error, try `rustc --explain E0283`. +For more information about this error, try `rustc --explain E0790`. error: could not compile `traits-example` due to previous error diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt index d6fffc967..104f2cf0f 100644 --- a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt @@ -7,7 +7,7 @@ error[E0746]: return type cannot have an unboxed trait object | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = note: for information on `impl Trait`, see -help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:14]`, which implements `Fn(i32) -> i32` +help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:8]`, which implements `Fn(i32) -> i32` | 1 | fn returns_closure() -> impl Fn(i32) -> i32 { | ~~~~~~~~~~~~~~~~~~~ diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt b/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt index 4402092e9..a6c9e8d3b 100644 --- a/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt @@ -1,13 +1,13 @@ $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference - --> src/lib.rs:52:13 - | -52 | worker.thread.join().unwrap(); - | ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call - | | - | move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait - | + --> src/lib.rs:52:13 + | +52 | worker.thread.join().unwrap(); + | ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call + | | + | move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait + | note: this function takes ownership of the receiver `self`, which moves `worker.thread` For more information about this error, try `rustc --explain E0507`. diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt index 34d30fe05..e4c0eeb2a 100644 --- a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt @@ -5,6 +5,12 @@ error[E0599]: no method named `join` found for enum `Option` in the current scop | 52 | worker.thread.join().unwrap(); | ^^^^ method not found in `Option>` + | +note: the method `join` exists on the type `JoinHandle<()>` +help: consider using `Option::expect` to unwrap the `JoinHandle<()>` value, panicking if the value is an `Option::None` + | +52 | worker.thread.expect("REASON").join().unwrap(); + | +++++++++++++++++ error[E0308]: mismatched types --> src/lib.rs:72:22 diff --git a/src/doc/book/rust-toolchain b/src/doc/book/rust-toolchain index 0a03ace41..5b6cd6b3c 100644 --- a/src/doc/book/rust-toolchain +++ b/src/doc/book/rust-toolchain @@ -1 +1 @@ -1.62 +1.65 diff --git a/src/doc/book/src/ch05-00-structs.md b/src/doc/book/src/ch05-00-structs.md index ff540b77d..d41482579 100644 --- a/src/doc/book/src/ch05-00-structs.md +++ b/src/doc/book/src/ch05-00-structs.md @@ -11,4 +11,4 @@ We’ll demonstrate how to define and instantiate structs. We’ll discuss how t define associated functions, especially the kind of associated functions called *methods*, to specify behavior associated with a struct type. Structs and enums (discussed in Chapter 6) are the building blocks for creating new types in your -program’s domain to take full advantage of Rust’s compile time type checking. +program’s domain to take full advantage of Rust’s compile-time type checking. diff --git a/src/doc/book/src/ch05-01-defining-structs.md b/src/doc/book/src/ch05-01-defining-structs.md index 7a50f99a5..d258d89cc 100644 --- a/src/doc/book/src/ch05-01-defining-structs.md +++ b/src/doc/book/src/ch05-01-defining-structs.md @@ -13,6 +13,8 @@ grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call *fields*. For example, Listing 5-1 shows a struct that stores information about a user account. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs:here}} ``` @@ -21,14 +23,16 @@ struct that stores information about a user account. To use a struct after we’ve defined it, we create an *instance* of that struct by specifying concrete values for each of the fields. We create an instance by -stating the name of the struct and then add curly brackets containing `key: -value` pairs, where the keys are the names of the fields and the values are the +stating the name of the struct and then add curly brackets containing *key: +value* pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don’t have to specify the fields in the same order in which we declared them in the struct. In other words, the struct definition is like a general template for the type, and instances fill in that template with particular data to create values of the type. For example, we can declare a particular user as shown in Listing 5-2. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs:here}} ``` @@ -42,6 +46,8 @@ mutable, we can change a value by using the dot notation and assigning into a particular field. Listing 5-3 shows how to change the value in the `email` field of a mutable `User` instance. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs:here}} ``` @@ -58,6 +64,8 @@ Listing 5-4 shows a `build_user` function that returns a `User` instance with the given email and username. The `active` field gets the value of `true`, and the `sign_in_count` gets a value of `1`. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs:here}} ``` @@ -70,20 +78,24 @@ fields, but having to repeat the `email` and `username` field names and variables is a bit tedious. If the struct had more fields, repeating each name would get even more annoying. Luckily, there’s a convenient shorthand! + + ### Using the Field Init Shorthand Because the parameter names and the struct field names are exactly the same in Listing 5-4, we can use the *field init shorthand* syntax to rewrite -`build_user` so that it behaves exactly the same but doesn’t have the -repetition of `email` and `username`, as shown in Listing 5-5. +`build_user` so it behaves exactly the same but doesn’t have the repetition of +`username` and `email`, as shown in Listing 5-5. + +Filename: src/main.rs ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs:here}} ``` Listing 5-5: A `build_user` function that uses field init -shorthand because the `email` and `username` parameters have the same name as +shorthand because the `username` and `email` parameters have the same name as struct fields Here, we’re creating a new instance of the `User` struct, which has a field @@ -92,7 +104,7 @@ named `email`. We want to set the `email` field’s value to the value in the the `email` parameter have the same name, we only need to write `email` rather than `email: email`. -### Creating Instances From Other Instances With Struct Update Syntax +### Creating Instances from Other Instances with Struct Update Syntax It’s often useful to create a new instance of a struct that includes most of the values from another instance, but changes some. You can do this using @@ -102,6 +114,8 @@ First, in Listing 5-6 we show how to create a new `User` instance in `user2` regularly, without the update syntax. We set a new value for `email` but otherwise use the same values from `user1` that we created in Listing 5-2. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs:here}} ``` @@ -113,12 +127,14 @@ Using struct update syntax, we can achieve the same effect with less code, as shown in Listing 5-7. The syntax `..` specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance. +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs:here}} ``` Listing 5-7: Using struct update syntax to set a new -`email` value for a `User` instance but use the rest of the values from +`email` value for a `User` instance but to use the rest of the values from `user1` The code in Listing 5-7 also creates an instance in `user2` that has a @@ -129,35 +145,37 @@ corresponding fields in `user1`, but we can choose to specify values for as many fields as we want in any order, regardless of the order of the fields in the struct’s definition. -Note that the struct update syntax uses `=` like an assignment; this is -because it moves the data, just as we saw in the [“Ways Variables and Data -Interact: Move”][move] section. In this example, we can no -longer use `user1` after creating `user2` because the `String` in the +Note that the struct update syntax uses `=` like an assignment; this is because +it moves the data, just as we saw in the [“Variables and Data Interacting with +Move”][move] section. In this example, we can no longer use +`user1` as a whole after creating `user2` because the `String` in the `username` field of `user1` was moved into `user2`. If we had given `user2` new `String` values for both `email` and `username`, and thus only used the `active` and `sign_in_count` values from `user1`, then `user1` would still be -valid after creating `user2`. The types of `active` and `sign_in_count` are -types that implement the `Copy` trait, so the behavior we discussed in the -[“Stack-Only Data: Copy”][copy] section would apply. +valid after creating `user2`. Both `active` and `sign_in_count` are types that +implement the `Copy` trait, so the behavior we discussed in the [“Stack-Only +Data: Copy”][copy] section would apply. -### Using Tuple Structs without Named Fields to Create Different Types +### Using Tuple Structs Without Named Fields to Create Different Types -Rust also supports structs that look similar to tuples, called *tuple -structs*. Tuple structs have the added meaning the struct name provides but -don’t have names associated with their fields; rather, they just have the types -of the fields. Tuple structs are useful when you want to give the whole tuple a -name and make the tuple a different type from other tuples, and when naming each +Rust also supports structs that look similar to tuples, called *tuple structs*. +Tuple structs have the added meaning the struct name provides but don’t have +names associated with their fields; rather, they just have the types of the +fields. Tuple structs are useful when you want to give the whole tuple a name +and make the tuple a different type from other tuples, and when naming each field as in a regular struct would be verbose or redundant. To define a tuple struct, start with the `struct` keyword and the struct name -followed by the types in the tuple. For example, here we define and use -two tuple structs named `Color` and `Point`: +followed by the types in the tuple. For example, here we define and use two +tuple structs named `Color` and `Point`: + +Filename: src/main.rs ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs}} ``` -Note that the `black` and `origin` values are different types, because they’re +Note that the `black` and `origin` values are different types because they’re instances of different tuple structs. Each struct you define is its own type, even though the fields within the struct might have the same types. For example, a function that takes a parameter of type `Color` cannot take a @@ -176,12 +194,14 @@ have any data that you want to store in the type itself. We’ll discuss traits in Chapter 10. Here’s an example of declaring and instantiating a unit struct named `AlwaysEqual`: +Filename: src/main.rs + ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-04-unit-like-structs/src/main.rs}} ``` -To define `AlwaysEqual`, we use the `struct` keyword, the name we want, then a -semicolon. No need for curly brackets or parentheses! Then we can get an +To define `AlwaysEqual`, we use the `struct` keyword, the name we want, and +then a semicolon. No need for curly brackets or parentheses! Then we can get an instance of `AlwaysEqual` in the `subject` variable in a similar way: using the name we defined, without any curly brackets or parentheses. Imagine that later we’ll implement behavior for this type such that every instance of @@ -217,9 +237,9 @@ implement them on any type, including unit-like structs. > > fn main() { > let user1 = User { -> email: "someone@example.com", -> username: "someusername123", > active: true, +> username: "someusername123", +> email: "someone@example.com", > sign_in_count: 1, > }; > } @@ -273,5 +293,5 @@ paste above add `> ` before every line --> [tuples]: ch03-02-data-types.html#the-tuple-type -[move]: ch04-01-what-is-ownership.html#ways-variables-and-data-interact-move +[move]: ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move [copy]: ch04-01-what-is-ownership.html#stack-only-data-copy diff --git a/src/doc/book/src/ch05-02-example-structs.md b/src/doc/book/src/ch05-02-example-structs.md index 5d33d9cb1..b2416b743 100644 --- a/src/doc/book/src/ch05-02-example-structs.md +++ b/src/doc/book/src/ch05-02-example-structs.md @@ -82,8 +82,8 @@ parts, as shown in Listing 5-10. Here we’ve defined a struct and named it `Rectangle`. Inside the curly brackets, we defined the fields as `width` and `height`, both of which have -type `u32`. Then in `main`, we created a particular instance of `Rectangle` -that has a width of 30 and a height of 50. +type `u32`. Then, in `main`, we created a particular instance of `Rectangle` +that has a width of `30` and a height of `50`. Our `area` function is now defined with one parameter, which we’ve named `rectangle`, whose type is an immutable borrow of a struct `Rectangle` @@ -126,7 +126,7 @@ When we compile this code, we get an error with this core message: The `println!` macro can do many kinds of formatting, and by default, the curly brackets tell `println!` to use formatting known as `Display`: output intended for direct end user consumption. The primitive types we’ve seen so far -implement `Display` by default, because there’s only one way you’d want to show +implement `Display` by default because there’s only one way you’d want to show a `1` or any other primitive type to a user. But with structs, the way `println!` should format the output is less clear because there are more display possibilities: Do you want commas or not? Do you want to print the @@ -182,8 +182,8 @@ following output: Nice! It’s not the prettiest output, but it shows the values of all the fields for this instance, which would definitely help during debugging. When we have larger structs, it’s useful to have output that’s a bit easier to read; in -those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. -In this example, using the `{:#?}` style will output: +those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. In +this example, using the `{:#?}` style will output the following: ```console {{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt}} @@ -191,15 +191,15 @@ In this example, using the `{:#?}` style will output: Another way to print out a value using the `Debug` format is to use the [`dbg!` macro][dbg], which takes ownership of an expression (as opposed -to `println!` that takes a reference), prints the file and line number of where -that `dbg!` macro call occurs in your code along with the resulting value of -that expression, and returns ownership of the value. +to `println!`, which takes a reference), prints the file and line number of +where that `dbg!` macro call occurs in your code along with the resultant value +of that expression, and returns ownership of the value. > Note: Calling the `dbg!` macro prints to the standard error console stream -> (`stderr`), as opposed to `println!` which prints to the standard output +> (`stderr`), as opposed to `println!`, which prints to the standard output > console stream (`stdout`). We’ll talk more about `stderr` and `stdout` in the -> [“Writing Error Messages to Standard Error Instead of Standard -> Output” section in Chapter 12][err]. +> [“Writing Error Messages to Standard Error Instead of Standard Output” +> section in Chapter 12][err]. Here’s an example where we’re interested in the value that gets assigned to the `width` field, as well as the value of the whole struct in `rect1`: @@ -218,8 +218,8 @@ Here’s what the output of this example looks like: {{#include ../listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/output.txt}} ``` -We can see the first bit of output came from *src/main.rs* line 10, where we’re -debugging the expression `30 * scale`, and its resulting value is 60 (the +We can see the first bit of output came from *src/main.rs* line 10 where we’re +debugging the expression `30 * scale`, and its resultant value is `60` (the `Debug` formatting implemented for integers is to print only their value). The `dbg!` call on line 14 of *src/main.rs* outputs the value of `&rect1`, which is the `Rectangle` struct. This output uses the pretty `Debug` formatting of the @@ -235,10 +235,10 @@ attributes other than `derive`; for more information, see [the “Attributes” section of the Rust Reference][attributes]. Our `area` function is very specific: it only computes the area of rectangles. -It would be helpful to tie this behavior more closely to our `Rectangle` -struct, because it won’t work with any other type. Let’s look at how we can -continue to refactor this code by turning the `area` function into an `area` -*method* defined on our `Rectangle` type. +It would be helpful to tie this behavior more closely to our `Rectangle` struct +because it won’t work with any other type. Let’s look at how we can continue to +refactor this code by turning the `area` function into an `area` *method* +defined on our `Rectangle` type. [the-tuple-type]: ch03-02-data-types.html#the-tuple-type [app-c]: appendix-03-derivable-traits.md diff --git a/src/doc/book/src/ch05-03-method-syntax.md b/src/doc/book/src/ch05-03-method-syntax.md index e300d0104..d25e55b18 100644 --- a/src/doc/book/src/ch05-03-method-syntax.md +++ b/src/doc/book/src/ch05-03-method-syntax.md @@ -4,9 +4,10 @@ name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Unlike functions, methods are defined within the context of a struct (or an enum or a trait -object, which we cover in Chapters 6 and 17, respectively), and their first -parameter is always `self`, which represents the instance of the struct the -method is being called on. +object, which we cover in [Chapter 6][enums] and [Chapter +17][trait-objects], respectively), and their first parameter is +always `self`, which represents the instance of the struct the method is being +called on. ### Defining Methods @@ -39,28 +40,30 @@ type `Self` is an alias for the type that the `impl` block is for. Methods must have a parameter named `self` of type `Self` for their first parameter, so Rust lets you abbreviate this with only the name `self` in the first parameter spot. Note that we still need to use the `&` in front of the `self` shorthand to -indicate this method borrows the `Self` instance, just as we did in `rectangle: -&Rectangle`. Methods can take ownership of `self`, borrow `self` immutably as -we’ve done here, or borrow `self` mutably, just as they can any other parameter. - -We’ve chosen `&self` here for the same reason we used `&Rectangle` in the -function version: we don’t want to take ownership, and we just want to read the -data in the struct, not write to it. If we wanted to change the instance that -we’ve called the method on as part of what the method does, we’d use `&mut -self` as the first parameter. Having a method that takes ownership of the -instance by using just `self` as the first parameter is rare; this technique is -usually used when the method transforms `self` into something else and you want -to prevent the caller from using the original instance after the transformation. - -The main reason for using methods instead of functions, in addition to providing -method syntax and not having to repeat the type of `self` in every method’s -signature, is for organization. We’ve put all the things we can do with an -instance of a type in one `impl` block rather than making future users of our -code search for capabilities of `Rectangle` in various places in the library we -provide. +indicate that this method borrows the `Self` instance, just as we did in +`rectangle: &Rectangle`. Methods can take ownership of `self`, borrow `self` +immutably, as we’ve done here, or borrow `self` mutably, just as they can any +other parameter. + +We chose `&self` here for the same reason we used `&Rectangle` in the function +version: we don’t want to take ownership, and we just want to read the data in +the struct, not write to it. If we wanted to change the instance that we’ve +called the method on as part of what the method does, we’d use `&mut self` as +the first parameter. Having a method that takes ownership of the instance by +using just `self` as the first parameter is rare; this technique is usually +used when the method transforms `self` into something else and you want to +prevent the caller from using the original instance after the transformation. + +The main reason for using methods instead of functions, in addition to +providing method syntax and not having to repeat the type of `self` in every +method’s signature, is for organization. We’ve put all the things we can do +with an instance of a type in one `impl` block rather than making future users +of our code search for capabilities of `Rectangle` in various places in the +library we provide. Note that we can choose to give a method the same name as one of the struct’s -fields. For example, we can define a method on `Rectangle` also named `width`: +fields. For example, we can define a method on `Rectangle` that is also named +`width`: Filename: src/main.rs @@ -69,19 +72,20 @@ fields. For example, we can define a method on `Rectangle` also named `width`: ``` Here, we’re choosing to make the `width` method return `true` if the value in -the instance’s `width` field is greater than 0, and `false` if the value is 0: -we can use a field within a method of the same name for any purpose. In `main`, -when we follow `rect1.width` with parentheses, Rust knows we mean the method -`width`. When we don’t use parentheses, Rust knows we mean the field `width`. - -Often, but not always, when we give methods with the same name as a field we -want it to only return the value in the field and do nothing else. Methods like -this are called *getters*, and Rust does not implement them automatically for -struct fields as some other languages do. Getters are useful because you can -make the field private but the method public and thus enable read-only access -to that field as part of the type’s public API. We will be discussing what -public and private are and how to designate a field or method as public or -private in Chapter 7. +the instance’s `width` field is greater than `0` and `false` if the value is +`0`: we can use a field within a method of the same name for any purpose. In +`main`, when we follow `rect1.width` with parentheses, Rust knows we mean the +method `width`. When we don’t use parentheses, Rust knows we mean the field +`width`. + +Often, but not always, when we give a method the same name as a field we want +it to only return the value in the field and do nothing else. Methods like this +are called *getters*, and Rust does not implement them automatically for struct +fields as some other languages do. Getters are useful because you can make the +field private but the method public, and thus enable read-only access to that +field as part of the type’s public API. We will discuss what public and private +are and how to designate a field or method as public or private in [Chapter +7][public]. > ### Where’s the `->` Operator? > @@ -131,11 +135,11 @@ private in Chapter 7. ### Methods with More Parameters Let’s practice using methods by implementing a second method on the `Rectangle` -struct. This time, we want an instance of `Rectangle` to take another instance +struct. This time we want an instance of `Rectangle` to take another instance of `Rectangle` and return `true` if the second `Rectangle` can fit completely -within `self` (the first `Rectangle`); otherwise it should return `false`. That -is, once we’ve defined the `can_hold` method, we want to be able to write the -program shown in Listing 5-14. +within `self` (the first `Rectangle`); otherwise, it should return `false`. +That is, once we’ve defined the `can_hold` method, we want to be able to write +the program shown in Listing 5-14. Filename: src/main.rs @@ -146,8 +150,8 @@ program shown in Listing 5-14. Listing 5-14: Using the as-yet-unwritten `can_hold` method -And the expected output would look like the following, because both dimensions -of `rect2` are smaller than the dimensions of `rect1` but `rect3` is wider than +The expected output would look like the following because both dimensions of +`rect2` are smaller than the dimensions of `rect1`, but `rect3` is wider than `rect1`: ```text @@ -165,7 +169,7 @@ read `rect2` (rather than write, which would mean we’d need a mutable borrow), and we want `main` to retain ownership of `rect2` so we can use it again after calling the `can_hold` method. The return value of `can_hold` will be a Boolean, and the implementation will check whether the width and height of -`self` are both greater than the width and height of the other `Rectangle`, +`self` are greater than the width and height of the other `Rectangle`, respectively. Let’s add the new `can_hold` method to the `impl` block from Listing 5-13, shown in Listing 5-15. @@ -213,13 +217,14 @@ is `Rectangle`. To call this associated function, we use the `::` syntax with the struct name; `let sq = Rectangle::square(3);` is an example. This function is namespaced by the struct: the `::` syntax is used for both associated functions and -namespaces created by modules. We’ll discuss modules in Chapter 7. +namespaces created by modules. We’ll discuss modules in [Chapter +7][modules]. ### Multiple `impl` Blocks Each struct is allowed to have multiple `impl` blocks. For example, Listing -5-15 is equivalent to the code shown in Listing 5-16, which has each method -in its own `impl` block. +5-15 is equivalent to the code shown in Listing 5-16, which has each method in +its own `impl` block. ```rust {{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs:here}} @@ -243,3 +248,8 @@ structs have. But structs aren’t the only way you can create custom types: let’s turn to Rust’s enum feature to add another tool to your toolbox. + +[enums]: ch06-00-enums.html +[trait-objects]: ch17-02-trait-objects.md +[public]: ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword +[modules]: ch07-02-defining-modules-to-control-scope-and-privacy.html diff --git a/src/doc/book/src/ch06-00-enums.md b/src/doc/book/src/ch06-00-enums.md index e207aa7bd..8a7faa9f3 100644 --- a/src/doc/book/src/ch06-00-enums.md +++ b/src/doc/book/src/ch06-00-enums.md @@ -1,7 +1,7 @@ # Enums and Pattern Matching -In this chapter we’ll look at *enumerations*, also referred to as *enums*. -Enums allow you to define a type by enumerating its possible *variants*. First, +In this chapter, we’ll look at *enumerations*, also referred to as *enums*. +Enums allow you to define a type by enumerating its possible *variants*. First we’ll define and use an enum to show how an enum can encode meaning along with data. Next, we’ll explore a particularly useful enum, called `Option`, which expresses that a value can be either something or nothing. Then we’ll look at diff --git a/src/doc/book/src/ch06-01-defining-an-enum.md b/src/doc/book/src/ch06-01-defining-an-enum.md index cb5d73097..eacd091bd 100644 --- a/src/doc/book/src/ch06-01-defining-an-enum.md +++ b/src/doc/book/src/ch06-01-defining-an-enum.md @@ -15,7 +15,7 @@ variants, which is where enumeration gets its name. Any IP address can be either a version four or a version six address, but not both at the same time. That property of IP addresses makes the enum data -structure appropriate, because an enum value can only be one of its variants. +structure appropriate because an enum value can only be one of its variants. Both version four and version six addresses are still fundamentally IP addresses, so they should be treated as the same type when the code is handling situations that apply to any kind of IP address. @@ -85,7 +85,7 @@ variants will have associated `String` values: ``` We attach data to each variant of the enum directly, so there is no need for an -extra struct. Here it’s also easier to see another detail of how enums work: +extra struct. Here, it’s also easier to see another detail of how enums work: the name of each enum variant that we define also becomes a function that constructs an instance of the enum. That is, `IpAddr::V4()` is a function call that takes a `String` argument and returns an instance of the `IpAddr` type. We @@ -93,7 +93,7 @@ automatically get this constructor function defined as a result of defining the enum. There’s another advantage to using an enum rather than a struct: each variant -can have different types and amounts of associated data. Version four type IP +can have different types and amounts of associated data. Version four IP addresses will always have four numeric components that will have values between 0 and 255. If we wanted to store `V4` addresses as four `u8` values but still express `V6` addresses as one `String` value, we wouldn’t be able to with @@ -150,7 +150,7 @@ different amounts and types of values This enum has four variants with different types: * `Quit` has no data associated with it at all. -* `Move` has named fields like a struct does. +* `Move` has named fields, like a struct does. * `Write` includes a single `String`. * `ChangeColor` includes three `i32` values. @@ -164,7 +164,7 @@ variants hold: {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs:here}} ``` -But if we used the different structs, which each have their own type, we +But if we used the different structs, each of which has its own type, we couldn’t as easily define a function to take any of these kinds of messages as we could with the `Message` enum defined in Listing 6-2, which is a single type. @@ -190,8 +190,8 @@ This section explores a case study of `Option`, which is another enum defined by the standard library. The `Option` type encodes the very common scenario in which a value could be something or it could be nothing. -For example, if you request the first of a list containing items, you would get -a value. If you request the first item of an empty list, you would get nothing. +For example, if you request the first item in a non-empty list, you would get +a value. If you request the first item in an empty list, you would get nothing. Expressing this concept in terms of the type system means the compiler can check whether you’ve handled all the cases you should be handling; this functionality can prevent bugs that are extremely common in other programming @@ -243,11 +243,11 @@ prefix. The `Option` enum is still just a regular enum, and `Some(T)` and The `` syntax is a feature of Rust we haven’t talked about yet. It’s a generic type parameter, and we’ll cover generics in more detail in Chapter 10. -For now, all you need to know is that `` means the `Some` variant of the -`Option` enum can hold one piece of data of any type, and that each concrete -type that gets used in place of `T` makes the overall `Option` type a -different type. Here are some examples of using `Option` values to hold number -types and string types: +For now, all you need to know is that `` means that the `Some` variant of +the `Option` enum can hold one piece of data of any type, and that each +concrete type that gets used in place of `T` makes the overall `Option` type +a different type. Here are some examples of using `Option` values to hold +number types and string types: ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs:here}} @@ -262,20 +262,20 @@ type that the corresponding `Some` variant will hold by looking only at a `Option`. When we have a `Some` value, we know that a value is present and the value is -held within the `Some`. When we have a `None` value, in some sense, it means -the same thing as null: we don’t have a valid value. So why is having -`Option` any better than having null? +held within the `Some`. When we have a `None` value, in some sense it means the +same thing as null: we don’t have a valid value. So why is having `Option` +any better than having null? In short, because `Option` and `T` (where `T` can be any type) are different types, the compiler won’t let us use an `Option` value as if it were -definitely a valid value. For example, this code won’t compile because it’s +definitely a valid value. For example, this code won’t compile, because it’s trying to add an `i8` to an `Option`: ```rust,ignore,does_not_compile {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs:here}} ``` -If we run this code, we get an error message like this: +If we run this code, we get an error message like this one: ```console {{#include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt}} @@ -292,8 +292,7 @@ using the value. In other words, you have to convert an `Option` to a `T` before you can perform `T` operations with it. Generally, this helps catch one of the most -common issues with null: assuming that something isn’t null when it actually -is. +common issues with null: assuming that something isn’t null when it actually is. Eliminating the risk of incorrectly assuming a not-null value helps you to be more confident in your code. In order to have a value that can possibly be @@ -304,20 +303,21 @@ when the value is null. Everywhere that a value has a type that isn’t an deliberate design decision for Rust to limit null’s pervasiveness and increase the safety of Rust code. -So, how do you get the `T` value out of a `Some` variant when you have a value -of type `Option` so you can use that value? The `Option` enum has a large -number of methods that are useful in a variety of situations; you can check -them out in [its documentation][docs]. Becoming familiar with -the methods on `Option` will be extremely useful in your journey with Rust. +So how do you get the `T` value out of a `Some` variant when you have a value +of type `Option` so that you can use that value? The `Option` enum has a +large number of methods that are useful in a variety of situations; you can +check them out in [its documentation][docs]. Becoming familiar +with the methods on `Option` will be extremely useful in your journey with +Rust. In general, in order to use an `Option` value, you want to have code that will handle each variant. You want some code that will run only when you have a `Some(T)` value, and this code is allowed to use the inner `T`. You want some -other code to run if you have a `None` value, and that code doesn’t have a `T` -value available. The `match` expression is a control flow construct that does -just this when used with enums: it will run different code depending on which -variant of the enum it has, and that code can use the data inside the matching -value. +other code to run only if you have a `None` value, and that code doesn’t have a +`T` value available. The `match` expression is a control flow construct that +does just this when used with enums: it will run different code depending on +which variant of the enum it has, and that code can use the data inside the +matching value. [IpAddr]: ../std/net/enum.IpAddr.html [option]: ../std/option/enum.Option.html diff --git a/src/doc/book/src/ch06-02-match.md b/src/doc/book/src/ch06-02-match.md index 2dfe6c34b..6a510df40 100644 --- a/src/doc/book/src/ch06-02-match.md +++ b/src/doc/book/src/ch06-02-match.md @@ -1,13 +1,15 @@ + ## The `match` Control Flow Construct -Rust has an extremely powerful control flow construct called `match` that allows -you to compare a value against a series of patterns and then execute code based -on which pattern matches. Patterns can be made up of literal values, variable -names, wildcards, and many other things; Chapter 18 covers all the different -kinds of patterns and what they do. The power of `match` comes from the -expressiveness of the patterns and the fact that the compiler confirms that all -possible cases are handled. +Rust has an extremely powerful control flow construct called `match` that +allows you to compare a value against a series of patterns and then execute +code based on which pattern matches. Patterns can be made up of literal values, +variable names, wildcards, and many other things; [Chapter +18][ch18-00-patterns] covers all the different kinds of patterns +and what they do. The power of `match` comes from the expressiveness of the +patterns and the fact that the compiler confirms that all possible cases are +handled. Think of a `match` expression as being like a coin-sorting machine: coins slide down a track with variously sized holes along it, and each coin falls through @@ -16,9 +18,9 @@ through each pattern in a `match`, and at the first pattern the value “fits, the value falls into the associated code block to be used during execution. Speaking of coins, let’s use them as an example using `match`! We can write a -function that takes an unknown United States coin and, in a similar way as the -counting machine, determines which coin it is and returns its value in cents, as -shown here in Listing 6-3. +function that takes an unknown US coin and, in a similar way as the counting +machine, determines which coin it is and returns its value in cents, as shown +in Listing 6-3. ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs:here}} @@ -27,25 +29,25 @@ shown here in Listing 6-3. Listing 6-3: An enum and a `match` expression that has the variants of the enum as its patterns -Let’s break down the `match` in the `value_in_cents` function. First, we list +Let’s break down the `match` in the `value_in_cents` function. First we list the `match` keyword followed by an expression, which in this case is the value -`coin`. This seems very similar to an expression used with `if`, but there’s a -big difference: with `if`, the expression needs to return a Boolean value, but -here, it can return any type. The type of `coin` in this example is the `Coin` -enum that we defined on the first line. +`coin`. This seems very similar to a conditional expression used with `if`, but +there’s a big difference: with `if`, the condition needs to evaluate to a +Boolean value, but here it can be any type. The type of `coin` in this example +is the `Coin` enum that we defined on the first line. Next are the `match` arms. An arm has two parts: a pattern and some code. The first arm here has a pattern that is the value `Coin::Penny` and then the `=>` operator that separates the pattern and the code to run. The code in this case is just the value `1`. Each arm is separated from the next with a comma. -When the `match` expression executes, it compares the resulting value against +When the `match` expression executes, it compares the resultant value against the pattern of each arm, in order. If a pattern matches the value, the code associated with that pattern is executed. If that pattern doesn’t match the value, execution continues to the next arm, much as in a coin-sorting machine. We can have as many arms as we need: in Listing 6-3, our `match` has four arms. -The code associated with each arm is an expression, and the resulting value of +The code associated with each arm is an expression, and the resultant value of the expression in the matching arm is the value that gets returned for the entire `match` expression. @@ -60,7 +62,7 @@ returns the last value of the block, `1`: {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs:here}} ``` -### Patterns that Bind to Values +### Patterns That Bind to Values Another useful feature of match arms is that they can bind to the parts of the values that match the pattern. This is how we can extract values out of enum @@ -70,8 +72,8 @@ As an example, let’s change one of our enum variants to hold data inside it. From 1999 through 2008, the United States minted quarters with different designs for each of the 50 states on one side. No other coins got state designs, so only quarters have this extra value. We can add this information to -our `enum` by changing the `Quarter` variant to include a `UsState` value stored -inside it, which we’ve done here in Listing 6-4. +our `enum` by changing the `Quarter` variant to include a `UsState` value +stored inside it, which we’ve done in Listing 6-4. ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs:here}} @@ -82,8 +84,8 @@ also holds a `UsState` value Let’s imagine that a friend is trying to collect all 50 state quarters. While we sort our loose change by coin type, we’ll also call out the name of the -state associated with each quarter so if it’s one our friend doesn’t have, they -can add it to their collection. +state associated with each quarter so that if it’s one our friend doesn’t have, +they can add it to their collection. In the match expression for this code, we add a variable called `state` to the pattern that matches values of the variant `Coin::Quarter`. When a @@ -104,10 +106,10 @@ state value out of the `Coin` enum variant for `Quarter`. ### Matching with `Option` In the previous section, we wanted to get the inner `T` value out of the `Some` -case when using `Option`; we can also handle `Option` using `match` as we -did with the `Coin` enum! Instead of comparing coins, we’ll compare the -variants of `Option`, but the way that the `match` expression works remains -the same. +case when using `Option`; we can also handle `Option` using `match`, as +we did with the `Coin` enum! Instead of comparing coins, we’ll compare the +variants of `Option`, but the way the `match` expression works remains the +same. Let’s say we want to write a function that takes an `Option` and, if there’s a value inside, adds 1 to that value. If there isn’t a value inside, @@ -126,26 +128,26 @@ an `Option` Let’s examine the first execution of `plus_one` in more detail. When we call `plus_one(five)`, the variable `x` in the body of `plus_one` will have the -value `Some(5)`. We then compare that against each match arm. +value `Some(5)`. We then compare that against each match arm: ```rust,ignore {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}} ``` The `Some(5)` value doesn’t match the pattern `None`, so we continue to the -next arm. +next arm: ```rust,ignore {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:second_arm}} ``` -Does `Some(5)` match `Some(i)`? Why yes it does! We have the same variant. The -`i` binds to the value contained in `Some`, so `i` takes the value `5`. The -code in the match arm is then executed, so we add 1 to the value of `i` and -create a new `Some` value with our total `6` inside. +Does `Some(5)` match `Some(i)`? It does! We have the same variant. The `i` +binds to the value contained in `Some`, so `i` takes the value `5`. The code in +the match arm is then executed, so we add 1 to the value of `i` and create a +new `Some` value with our total `6` inside. Now let’s consider the second call of `plus_one` in Listing 6-5, where `x` is -`None`. We enter the `match` and compare to the first arm. +`None`. We enter the `match` and compare to the first arm: ```rust,ignore {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}} @@ -179,7 +181,7 @@ error: {{#include ../listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt}} ``` -Rust knows that we didn’t cover every possible case and even knows which +Rust knows that we didn’t cover every possible case, and even knows which pattern we forgot! Matches in Rust are *exhaustive*: we must exhaust every last possibility in order for the code to be valid. Especially in the case of `Option`, when Rust prevents us from forgetting to explicitly handle the @@ -202,10 +204,10 @@ this example: {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-15-binding-catchall/src/main.rs:here}} ``` -For the first two arms, the patterns are the literal values 3 and 7. For the -last arm that covers every other possible value, the pattern is the variable -we’ve chosen to name `other`. The code that runs for the `other` arm uses the -variable by passing it to the `move_player` function. +For the first two arms, the patterns are the literal values `3` and `7`. For +the last arm that covers every other possible value, the pattern is the +variable we’ve chosen to name `other`. The code that runs for the `other` arm +uses the variable by passing it to the `move_player` function. This code compiles, even though we haven’t listed all the possible values a `u8` can have, because the last pattern will match all values not specifically @@ -230,7 +232,7 @@ can change our code to use `_` instead of the variable named `other`: This example also meets the exhaustiveness requirement because we’re explicitly ignoring all other values in the last arm; we haven’t forgotten anything. -Finally, we’ll change the rules of the game one more time, so that nothing else +Finally, we’ll change the rules of the game one more time so that nothing else happens on your turn if you roll anything other than a 3 or a 7. We can express that by using the unit value (the empty tuple type we mentioned in [“The Tuple Type”][tuples] section) as the code that goes with the `_` arm: diff --git a/src/doc/book/src/ch06-03-if-let.md b/src/doc/book/src/ch06-03-if-let.md index 07634e162..c9bfbf3c7 100644 --- a/src/doc/book/src/ch06-03-if-let.md +++ b/src/doc/book/src/ch06-03-if-let.md @@ -2,8 +2,9 @@ The `if let` syntax lets you combine `if` and `let` into a less verbose way to handle values that match one pattern while ignoring the rest. Consider the -program in Listing 6-6 that matches on an `Option` value in the `config_max` -variable but only wants to execute code if the value is the `Some` variant. +program in Listing 6-6 that matches on an `Option` value in the +`config_max` variable but only wants to execute code if the value is the `Some` +variant. ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs:here}} @@ -29,7 +30,7 @@ The syntax `if let` takes a pattern and an expression separated by an equal sign. It works the same way as a `match`, where the expression is given to the `match` and the pattern is its first arm. In this case, the pattern is `Some(max)`, and the `max` binds to the value inside the `Some`. We can then -use `max` in the body of the `if let` block in the same way as we used `max` in +use `max` in the body of the `if let` block in the same way we used `max` in the corresponding `match` arm. The code in the `if let` block isn’t run if the value doesn’t match the pattern. @@ -48,13 +49,13 @@ We can include an `else` with an `if let`. The block of code that goes with the `Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a `UsState` value. If we wanted to count all non-quarter coins we see while also announcing the state of the quarters, we could do that with a `match` -expression like this: +expression, like this: ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs:here}} ``` -Or we could use an `if let` and `else` expression like this: +Or we could use an `if let` and `else` expression, like this: ```rust {{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs:here}} @@ -73,9 +74,10 @@ values, depending on how many cases you need to handle. Your Rust programs can now express concepts in your domain using structs and enums. Creating custom types to use in your API ensures type safety: the -compiler will make certain your functions get only values of the type each +compiler will make certain your functions only get values of the type each function expects. In order to provide a well-organized API to your users that is straightforward to use and only exposes exactly what your users will need, let’s now turn to Rust’s modules. + diff --git a/src/doc/book/src/title-page.md b/src/doc/book/src/title-page.md index ed55a6839..12d1a6598 100644 --- a/src/doc/book/src/title-page.md +++ b/src/doc/book/src/title-page.md @@ -2,7 +2,7 @@ *by Steve Klabnik and Carol Nichols, with contributions from the Rust Community* -This version of the text assumes you’re using Rust 1.62 (released 2022-06-30) +This version of the text assumes you’re using Rust 1.65 (released 2022-11-03) or later. See the [“Installation” section of Chapter 1][install] to install or update Rust. diff --git a/src/doc/embedded-book/src/intro/install/linux.md b/src/doc/embedded-book/src/intro/install/linux.md index f8684d0a8..1c0b0edfa 100644 --- a/src/doc/embedded-book/src/intro/install/linux.md +++ b/src/doc/embedded-book/src/intro/install/linux.md @@ -39,16 +39,13 @@ sudo apt install gdb-arm-none-eabi openocd qemu-system-arm - Fedora 27 or newer -> **NOTE** `arm-none-eabi-gdb` is the GDB command you'll use to debug your ARM -> Cortex-M programs - ``` console -sudo dnf install arm-none-eabi-gdb openocd qemu-system-arm +sudo dnf install gdb openocd qemu-system-arm ``` - Arch Linux diff --git a/src/doc/embedded-book/src/intro/no-std.md b/src/doc/embedded-book/src/intro/no-std.md index 35bfc1adc..93aadf65d 100644 --- a/src/doc/embedded-book/src/intro/no-std.md +++ b/src/doc/embedded-book/src/intro/no-std.md @@ -47,7 +47,7 @@ bootstrapping (stage 0) code like bootloaders, firmware or kernels. | feature | no\_std | std | |-----------------------------------------------------------|--------|-----| | heap (dynamic memory) | * | ✓ | -| collections (Vec, HashMap, etc) | ** | ✓ | +| collections (Vec, BTreeMap, etc) | ** | ✓ | | stack overflow protection | ✘ | ✓ | | runs init code before main | ✘ | ✓ | | libstd available | ✘ | ✓ | @@ -58,6 +58,8 @@ bootstrapping (stage 0) code like bootloaders, firmware or kernels. \** Only if you use the `collections` crate and configure a global default allocator. +\** HashMap and HashSet are not available due to a lack of a secure random number generator. + [alloc-cortex-m]: https://github.com/rust-embedded/alloc-cortex-m ## See Also diff --git a/src/doc/embedded-book/src/peripherals/singletons.md b/src/doc/embedded-book/src/peripherals/singletons.md index 840a98665..3f04aa170 100644 --- a/src/doc/embedded-book/src/peripherals/singletons.md +++ b/src/doc/embedded-book/src/peripherals/singletons.md @@ -25,7 +25,7 @@ But this has a few problems. It is a mutable global variable, and in Rust, these ## How do we do this in Rust? -Instead of just making our peripheral a global variable, we might instead decide to make a global variable, in this case called `PERIPHERALS`, which contains an `Option` for each of our peripherals. +Instead of just making our peripheral a global variable, we might instead decide to make a structure, in this case called `PERIPHERALS`, which contains an `Option` for each of our peripherals. ```rust,ignore struct Peripherals { diff --git a/src/doc/embedded-book/src/start/hardware.md b/src/doc/embedded-book/src/start/hardware.md index f1eee3163..8166e62e5 100644 --- a/src/doc/embedded-book/src/start/hardware.md +++ b/src/doc/embedded-book/src/start/hardware.md @@ -272,7 +272,7 @@ Quit anyway? (y or n) ``` Debugging now requires a few more steps so we have packed all those steps into a -single GDB script named `openocd.gdb`. The file was created during the `cargo generate` step, and should work without any modifications. Let's have a peak: +single GDB script named `openocd.gdb`. The file was created during the `cargo generate` step, and should work without any modifications. Let's have a peek: ``` console cat openocd.gdb diff --git a/src/doc/nomicon/src/lifetime-mismatch.md b/src/doc/nomicon/src/lifetime-mismatch.md index 1da2d285c..bc53f06f8 100644 --- a/src/doc/nomicon/src/lifetime-mismatch.md +++ b/src/doc/nomicon/src/lifetime-mismatch.md @@ -74,7 +74,7 @@ care about, but the lifetime system is too coarse-grained to handle that. ## Improperly reduced borrows The following code fails to compile, because Rust sees that a variable, `map`, -is borrowed twice, and can not infer that the first borrow stops to be needed +is borrowed twice, and can not infer that the first borrow ceases to be needed before the second one occurs. This is caused by Rust conservatively falling back to using a whole scope for the first borrow. This will eventually get fixed. diff --git a/src/doc/nomicon/src/unchecked-uninit.md b/src/doc/nomicon/src/unchecked-uninit.md index c61415c97..b3dd31cf1 100644 --- a/src/doc/nomicon/src/unchecked-uninit.md +++ b/src/doc/nomicon/src/unchecked-uninit.md @@ -11,7 +11,7 @@ Unsafe Rust gives us a powerful tool to handle this problem: [`MaybeUninit`]. This type can be used to handle memory that has not been fully initialized yet. -With `MaybeUninit`, we can initialize an array element-for-element as follows: +With `MaybeUninit`, we can initialize an array element by element as follows: ```rust use std::mem::{self, MaybeUninit}; @@ -79,8 +79,7 @@ This code proceeds in three steps: acknowledge that by providing appropriate methods). It's worth spending a bit more time on the loop in the middle, and in particular -the assignment operator and its interaction with `drop`. If we would have -written something like: +the assignment operator and its interaction with `drop`. If we wrote something like: ```rust,ignore @@ -88,7 +87,7 @@ written something like: ``` we would actually overwrite a `Box`, leading to `drop` of uninitialized -data, which will cause much sadness and pain. +data, which would cause much sadness and pain. The correct alternative, if for some reason we cannot use `MaybeUninit::new`, is to use the [`ptr`] module. In particular, it provides three functions that allow @@ -97,7 +96,7 @@ us to assign bytes to a location in memory without dropping the old value: * `ptr::write(ptr, val)` takes a `val` and moves it into the address pointed to by `ptr`. -* `ptr::copy(src, dest, count)` copies the bits that `count` T's would occupy +* `ptr::copy(src, dest, count)` copies the bits that `count` T items would occupy from src to dest. (this is equivalent to C's memmove -- note that the argument order is reversed!) * `ptr::copy_nonoverlapping(src, dest, count)` does what `copy` does, but a @@ -105,8 +104,8 @@ us to assign bytes to a location in memory without dropping the old value: (this is equivalent to C's memcpy -- note that the argument order is reversed!) It should go without saying that these functions, if misused, will cause serious -havoc or just straight up Undefined Behavior. The only things that these -functions *themselves* require is that the locations you want to read and write +havoc or just straight up Undefined Behavior. The only requirement of these +functions *themselves* is that the locations you want to read and write are allocated and properly aligned. However, the ways writing arbitrary bits to arbitrary locations of memory can break things are basically uncountable! diff --git a/src/doc/nomicon/src/vec/vec-alloc.md b/src/doc/nomicon/src/vec/vec-alloc.md index 6c69c9379..249547339 100644 --- a/src/doc/nomicon/src/vec/vec-alloc.md +++ b/src/doc/nomicon/src/vec/vec-alloc.md @@ -28,7 +28,6 @@ impl Vec { ptr: NonNull::dangling(), len: 0, cap: 0, - _marker: PhantomData, } } } diff --git a/src/doc/nomicon/src/vec/vec-final.md b/src/doc/nomicon/src/vec/vec-final.md index 1f8af37ad..696391d10 100644 --- a/src/doc/nomicon/src/vec/vec-final.md +++ b/src/doc/nomicon/src/vec/vec-final.md @@ -10,7 +10,6 @@ use std::ptr::{self, NonNull}; struct RawVec { ptr: NonNull, cap: usize, - _marker: PhantomData, } unsafe impl Send for RawVec {} @@ -25,7 +24,6 @@ impl RawVec { RawVec { ptr: NonNull::dangling(), cap: cap, - _marker: PhantomData, } } diff --git a/src/doc/nomicon/src/vec/vec-insert-remove.md b/src/doc/nomicon/src/vec/vec-insert-remove.md index 57283f990..722e20c45 100644 --- a/src/doc/nomicon/src/vec/vec-insert-remove.md +++ b/src/doc/nomicon/src/vec/vec-insert-remove.md @@ -22,9 +22,11 @@ pub fn insert(&mut self, index: usize, elem: T) { unsafe { // ptr::copy(src, dest, len): "copy from src to dest len elems" - ptr::copy(self.ptr.as_ptr().add(index), - self.ptr.as_ptr().add(index + 1), - self.len - index); + ptr::copy( + self.ptr.as_ptr().add(index), + self.ptr.as_ptr().add(index + 1), + self.len - index, + ); ptr::write(self.ptr.as_ptr().add(index), elem); self.len += 1; } @@ -42,9 +44,11 @@ pub fn remove(&mut self, index: usize) -> T { unsafe { self.len -= 1; let result = ptr::read(self.ptr.as_ptr().add(index)); - ptr::copy(self.ptr.as_ptr().add(index + 1), - self.ptr.as_ptr().add(index), - self.len - index); + ptr::copy( + self.ptr.as_ptr().add(index + 1), + self.ptr.as_ptr().add(index), + self.len - index, + ); result } } diff --git a/src/doc/nomicon/src/vec/vec-into-iter.md b/src/doc/nomicon/src/vec/vec-into-iter.md index 61782e3b8..a3a3c8cb9 100644 --- a/src/doc/nomicon/src/vec/vec-into-iter.md +++ b/src/doc/nomicon/src/vec/vec-into-iter.md @@ -49,7 +49,6 @@ pub struct IntoIter { cap: usize, start: *const T, end: *const T, - _marker: PhantomData, } ``` @@ -61,13 +60,13 @@ impl IntoIterator for Vec { type Item = T; type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { - // Can't destructure Vec since it's Drop - let ptr = self.ptr; - let cap = self.cap; - let len = self.len; - // Make sure not to drop Vec since that would free the buffer - mem::forget(self); + let vec = ManuallyDrop::new(self); + + // Can't destructure Vec since it's Drop + let ptr = vec.ptr; + let cap = vec.cap; + let len = vec.len; unsafe { IntoIter { @@ -80,7 +79,6 @@ impl IntoIterator for Vec { } else { ptr.as_ptr().add(len) }, - _marker: PhantomData, } } } diff --git a/src/doc/nomicon/src/vec/vec-layout.md b/src/doc/nomicon/src/vec/vec-layout.md index c1c1afcc7..9129952a5 100644 --- a/src/doc/nomicon/src/vec/vec-layout.md +++ b/src/doc/nomicon/src/vec/vec-layout.md @@ -15,13 +15,10 @@ pub struct Vec { } ``` -And indeed this would compile. Unfortunately, it would be incorrect. First, the +And indeed this would compile. Unfortunately, it would be too strict. The compiler will give us too strict variance. So a `&Vec<&'static str>` -couldn't be used where an `&Vec<&'a str>` was expected. More importantly, it -will give incorrect ownership information to the drop checker, as it will -conservatively assume we don't own any values of type `T`. See [the chapter -on ownership and lifetimes][ownership] for all the details on variance and -drop check. +couldn't be used where a `&Vec<&'a str>` was expected. See [the chapter +on ownership and lifetimes][ownership] for all the details on variance. As we saw in the ownership chapter, the standard library uses `Unique` in place of `*mut T` when it has a raw pointer to an allocation that it owns. Unique is unstable, @@ -30,16 +27,16 @@ so we'd like to not use it if possible, though. As a recap, Unique is a wrapper around a raw pointer that declares that: * We are covariant over `T` -* We may own a value of type `T` (for drop check) +* We may own a value of type `T` (this is not relevant for our example here, but see + [the chapter on PhantomData][phantom-data] on why the real `std::vec::Vec` needs this) * We are Send/Sync if `T` is Send/Sync * Our pointer is never null (so `Option>` is null-pointer-optimized) We can implement all of the above requirements in stable Rust. To do this, instead of using `Unique` we will use [`NonNull`][NonNull], another wrapper around a raw pointer, which gives us two of the above properties, namely it is covariant -over `T` and is declared to never be null. By adding a `PhantomData` (for drop -check) and implementing Send/Sync if `T` is, we get the same results as using -`Unique`: +over `T` and is declared to never be null. By implementing Send/Sync if `T` is, +we get the same results as using `Unique`: ```rust use std::ptr::NonNull; @@ -49,7 +46,6 @@ pub struct Vec { ptr: NonNull, cap: usize, len: usize, - _marker: PhantomData, } unsafe impl Send for Vec {} @@ -58,4 +54,5 @@ unsafe impl Sync for Vec {} ``` [ownership]: ../ownership.html +[phantom-data]: ../phantom-data.md [NonNull]: ../../std/ptr/struct.NonNull.html diff --git a/src/doc/nomicon/src/vec/vec-raw.md b/src/doc/nomicon/src/vec/vec-raw.md index e86537b81..728feaa58 100644 --- a/src/doc/nomicon/src/vec/vec-raw.md +++ b/src/doc/nomicon/src/vec/vec-raw.md @@ -13,7 +13,6 @@ allocating, growing, and freeing: struct RawVec { ptr: NonNull, cap: usize, - _marker: PhantomData, } unsafe impl Send for RawVec {} @@ -25,7 +24,6 @@ impl RawVec { RawVec { ptr: NonNull::dangling(), cap: 0, - _marker: PhantomData, } } diff --git a/src/doc/nomicon/src/vec/vec-zsts.md b/src/doc/nomicon/src/vec/vec-zsts.md index 73a97ba49..8f2529727 100644 --- a/src/doc/nomicon/src/vec/vec-zsts.md +++ b/src/doc/nomicon/src/vec/vec-zsts.md @@ -33,14 +33,13 @@ method of `RawVec`. ```rust,ignore impl RawVec { fn new() -> Self { - // !0 is usize::MAX. This branch should be stripped at compile time. - let cap = if mem::size_of::() == 0 { !0 } else { 0 }; + // This branch should be stripped at compile time. + let cap = if mem::size_of::() == 0 { usize::MAX } else { 0 }; // `NonNull::dangling()` doubles as "unallocated" and "zero-sized allocation" RawVec { ptr: NonNull::dangling(), cap: cap, - _marker: PhantomData, } } diff --git a/src/doc/reference/src/attributes.md b/src/doc/reference/src/attributes.md index b7c1ef609..5d619c990 100644 --- a/src/doc/reference/src/attributes.md +++ b/src/doc/reference/src/attributes.md @@ -248,6 +248,7 @@ The following is an index of all built-in attributes. - [`no_builtins`] — Disables use of certain built-in functions. - [`target_feature`] — Configure platform-specific code generation. - [`track_caller`] - Pass the parent call location to `std::panic::Location::caller()`. + - [`instruction_set`] - Specify the instruction set used to generate a functions code - Documentation - `doc` — Specifies documentation. See [The Rustdoc Book] for more information. [Doc comments] are transformed into `doc` attributes. @@ -298,6 +299,7 @@ The following is an index of all built-in attributes. [`global_allocator`]: runtime.md#the-global_allocator-attribute [`ignore`]: attributes/testing.md#the-ignore-attribute [`inline`]: attributes/codegen.md#the-inline-attribute +[`instruction_set`]: attributes/codegen.md#the-instruction_set-attribute [`link_name`]: items/external-blocks.md#the-link_name-attribute [`link_ordinal`]: items/external-blocks.md#the-link_ordinal-attribute [`link_section`]: abi.md#the-link_section-attribute diff --git a/src/doc/reference/src/attributes/codegen.md b/src/doc/reference/src/attributes/codegen.md index 3a36a10ca..69ad341d1 100644 --- a/src/doc/reference/src/attributes/codegen.md +++ b/src/doc/reference/src/attributes/codegen.md @@ -352,3 +352,26 @@ trait object whose methods are attributed. [`core::intrinsics::caller_location`]: ../../core/intrinsics/fn.caller_location.html [`core::panic::Location::caller`]: ../../core/panic/struct.Location.html#method.caller [`Location`]: ../../core/panic/struct.Location.html + +## The `instruction_set` attribute + +The *`instruction_set` attribute* may be applied to a function to enable code generation for a specific +instruction set supported by the target architecture. It uses the [_MetaListPath_] syntax and a path +comprised of the architecture and instruction set to specify how to generate the code for +architectures where a single program may utilize multiple instruction sets. + +The following values are available on targets for the `ARMv4` and `ARMv5te` architectures: + +* `arm::a32` - Uses ARM code. +* `arm::t32` - Uses Thumb code. + + +```rust,ignore +#[instruction_set(arm::a32)] +fn foo_arm_code() {} + +#[instruction_set(arm::t32)] +fn bar_thumb_code() {} +``` + +[_MetaListPath_]: ../attributes.md#meta-item-attribute-syntax diff --git a/src/doc/reference/src/behavior-considered-undefined.md b/src/doc/reference/src/behavior-considered-undefined.md index e810e8c0d..f8bffd13e 100644 --- a/src/doc/reference/src/behavior-considered-undefined.md +++ b/src/doc/reference/src/behavior-considered-undefined.md @@ -26,8 +26,22 @@ code. * Evaluating a [dereference expression] (`*expr`) on a raw pointer that is [dangling] or unaligned, even in [place expression context] (e.g. `addr_of!(&*expr)`). -* Breaking the [pointer aliasing rules]. `&mut T` and `&T` follow LLVM’s scoped - [noalias] model, except if the `&T` contains an [`UnsafeCell`]. +* Breaking the [pointer aliasing rules]. `Box`, `&mut T` and `&T` follow + LLVM’s scoped [noalias] model, except if the `&T` contains an + [`UnsafeCell`]. References and boxes must not be [dangling] while they are + live. The exact liveness duration is not specified, but some bounds exist: + * For references, the liveness duration is upper-bounded by the syntactic + lifetime assigned by the borrow checker; it cannot be live any *longer* than + that lifetime. + * Each time a reference or box is passed to or returned from a function, it is + considered live. + * When a reference (but not a `Box`!) is passed to a function, it is live at + least as long as that function call, again except if the `&T` contains an + [`UnsafeCell`]. + + All this also applies when values of these + types are passed in a (nested) field of a compound type, but not behind + pointer indirections. * Mutating immutable data. All data inside a [`const`] item is immutable. Moreover, all data reached through a shared reference or data owned by an immutable binding is immutable, unless that data is contained within an [`UnsafeCell`]. diff --git a/src/doc/reference/src/comments.md b/src/doc/reference/src/comments.md index 46074b45c..ad29c58e5 100644 --- a/src/doc/reference/src/comments.md +++ b/src/doc/reference/src/comments.md @@ -2,7 +2,7 @@ > **Lexer**\ > LINE_COMMENT :\ ->       `//` (~\[`/` `!`] | `//`) ~`\n`\*\ +>       `//` (~\[`/` `!` `\n`] | `//`) ~`\n`\*\ >    | `//` > > BLOCK_COMMENT :\ diff --git a/src/doc/reference/src/expressions/literal-expr.md b/src/doc/reference/src/expressions/literal-expr.md index 4eec37dcb..e5bc2dff4 100644 --- a/src/doc/reference/src/expressions/literal-expr.md +++ b/src/doc/reference/src/expressions/literal-expr.md @@ -8,11 +8,9 @@ >    | [BYTE_LITERAL]\ >    | [BYTE_STRING_LITERAL]\ >    | [RAW_BYTE_STRING_LITERAL]\ ->    | [INTEGER_LITERAL][^out-of-range]\ +>    | [INTEGER_LITERAL]\ >    | [FLOAT_LITERAL]\ >    | `true` | `false` -> -> [^out-of-range]: A value ≥ 2128 is not allowed. A _literal expression_ is an expression consisting of a single token, rather than a sequence of tokens, that immediately and directly denotes the value it evaluates to, rather than referring to it by name or some other evaluation rule. @@ -54,7 +52,7 @@ A string literal expression consists of a single [BYTE_STRING_LITERAL] or [RAW_B An integer literal expression consists of a single [INTEGER_LITERAL] token. -If the token has a [suffix], the suffix will be the name of one of the [primitive integer types][numeric types]: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type. +If the token has a [suffix], the suffix must be the name of one of the [primitive integer types][numeric types]: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type. If the token has no suffix, the expression's type is determined by type inference: @@ -96,10 +94,12 @@ The value of the expression is determined from the string representation of the * If the radix is not 10, the first two characters are removed from the string. +* Any suffix is removed from the string. + * Any underscores are removed from the string. * The string is converted to a `u128` value as if by [`u128::from_str_radix`] with the chosen radix. -If the value does not fit in `u128`, the expression is rejected by the parser. +If the value does not fit in `u128`, it is a compiler error. * The `u128` value is converted to the expression's type via a [numeric cast]. @@ -111,9 +111,11 @@ If the value does not fit in `u128`, the expression is rejected by the parser. ## Floating-point literal expressions -A floating-point literal expression consists of a single [FLOAT_LITERAL] token. +A floating-point literal expression has one of two forms: + * a single [FLOAT_LITERAL] token + * a single [INTEGER_LITERAL] token which has a suffix and no radix indicator -If the token has a [suffix], the suffix will be the name of one of the [primitive floating-point types][floating-point types]: `f32` or `f64`, and the expression has that type. +If the token has a [suffix], the suffix must be the name of one of the [primitive floating-point types][floating-point types]: `f32` or `f64`, and the expression has that type. If the token has no suffix, the expression's type is determined by type inference: @@ -136,6 +138,8 @@ let x: f64 = 2.; // type f64 The value of the expression is determined from the string representation of the token as follows: +* Any suffix is removed from the string. + * Any underscores are removed from the string. * The string is converted to the expression's type as if by [`f32::from_str`] or [`f64::from_str`]. diff --git a/src/doc/reference/src/items/extern-crates.md b/src/doc/reference/src/items/extern-crates.md index f4dc735b0..d6b3a9aae 100644 --- a/src/doc/reference/src/items/extern-crates.md +++ b/src/doc/reference/src/items/extern-crates.md @@ -20,9 +20,9 @@ clause can be used to bind the imported crate to a different name. The external crate is resolved to a specific `soname` at compile time, and a runtime linkage requirement to that `soname` is passed to the linker for loading at runtime. The `soname` is resolved at compile time by scanning the -compiler's library path and matching the optional `crateid` provided against -the `crateid` attributes that were declared on the external crate when it was -compiled. If no `crateid` is provided, a default `name` attribute is assumed, +compiler's library path and matching the optional `crate_name` provided against +the [`crate_name` attributes] that were declared on the external crate when it was +compiled. If no `crate_name` is provided, a default `name` attribute is assumed, equal to the [identifier] given in the `extern crate` declaration. The `self` crate may be imported which creates a binding to the current crate. @@ -78,6 +78,7 @@ crate to access only its macros. [`macro_use` attribute]: ../macros-by-example.md#the-macro_use-attribute [extern prelude]: ../names/preludes.md#extern-prelude [`macro_use` prelude]: ../names/preludes.md#macro_use-prelude +[`crate_name` attributes]: ../crates-and-source-files.md#the-crate_name-attribute