Giter Club home page Giter Club logo

rust-book's Introduction

The Rust Programming Language

Build Status

This repository contains the source of "The Rust Programming Language" book, specifically an experimental branch that supports interactive features like quizzes.

If you discovered an issue in at https://rust-book.cs.brown.edu/, PLEASE report the issue on THIS REPOSITORY and not elsewhere.

The book is available in dead-tree form from No Starch Press.

You can also read the book for free online. Please see the book as shipped with the latest stable, beta, or nightly Rust releases. Be aware that issues in those versions may have been fixed in this repository already, as those releases are updated less frequently.

See the releases to download just the code of all the code listings that appear in the book.

Requirements

Building the book requires mdBook, ideally the same version that rust-lang/rust uses in this file. To get it:

$ cargo install mdbook --version <version_num>

This fork also requires a few mdBook preprocessors to support our experimental extensions. Follow the installation instructions at each link below.

You should install the same version of each preprocessor used in CI.

Finally, you need pnpm.

Building

With cargo-make

If you have cargo-make installed, then run:

$ cargo make build

Without cargo-make

First, build the Javascript extensions.

$ cd js-extensions
$ pnpm init-repo
$ cd ..

Then to build the book, type:

$ mdbook build

Output

The output will be in the book subdirectory. To check it out, open it in your web browser.

Firefox:

$ firefox book/index.html                       # Linux
$ open -a "Firefox" book/index.html             # OS X
$ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell)
$ start firefox.exe .\book\index.html           # Windows (Cmd)

Chrome:

$ google-chrome book/index.html                 # Linux
$ open -a "Google Chrome" book/index.html       # OS X
$ Start-Process "chrome.exe" .\book\index.html  # Windows (PowerShell)
$ start chrome.exe .\book\index.html            # Windows (Cmd)

To run the tests:

$ mdbook test

Contributing

We'd love your help! Please see CONTRIBUTING.md to learn about the kinds of contributions we're looking for.

Because the book is printed, and because we want to keep the online version of the book close to the print version when possible, it may take longer than you're used to for us to address your issue or pull request.

So far, we've been doing a larger revision to coincide with Rust Editions. Between those larger revisions, we will only be correcting errors. If your issue or pull request isn't strictly fixing an error, it might sit until the next time that we're working on a large revision: expect on the order of months or years. Thank you for your patience!

Translations

We'd love help translating the book! See the Translations label to join in efforts that are currently in progress. Open a new issue to start working on a new language! We're waiting on mdbook support for multiple languages before we merge any in, but feel free to start!

Spellchecking

To scan source files for spelling errors, you can use the spellcheck.sh script available in the ci directory. It needs a dictionary of valid words, which is provided in ci/dictionary.txt. If the script produces a false positive (say, you used word BTreeMap which the script considers invalid), you need to add this word to ci/dictionary.txt (keep the sorted order for consistency).

rust-book's People

Contributors

aaaxx avatar applejax avatar awaitlink avatar bmusin avatar carols10cents avatar chenl avatar clemensw avatar connorff avatar damoasda avatar davidde avatar dnaeon avatar ehuss avatar elahn avatar frewsxcv avatar grantmoyer avatar guillaumegomez avatar gypsydave5 avatar jightuse avatar josephtlyons avatar kornelski avatar lancelafontaine avatar mdesharnais avatar outkaj avatar passcod avatar pduzinki avatar ralfjung avatar sebras avatar spastorino avatar steveklabnik avatar willcrichton avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rust-book's Issues

Question: testing read permission of a path

I was reading your version of The Rust Book, and I find the read/write/own permission concept pretty interesting. But I have a question, and since I don't know where else to ask about this, I'm posting this here.
How do you test if a path is readable?

For example, you can test if a path has own and write permissions like this:

let mut s = String::from("hello world");
s = String::from("changed"); // `s` has write permission
let s_1 = s; // `s` has ownership permission

But how do you test if a path has read permission?

Incorrect wording in chapter 10.3

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch10-03-lifetime-syntax.html
Description of the problem:
The lifetime parameter declaration after impl and its use after the type name are required, but we’re not required to annotate the lifetime of the reference to self because of the first elision rule.
Suggested fix:
The lifetime parameter declaration after impl and its use after the type name are required, but we’re not required to annotate the lifetime of the reference to self because of the third elision rule.

Free before use?

This says that Rust frees and then allocates new larger memory. Perhaps it should say that Rust allocates a larger chunk of memory, writes "Ferris Jr." and then frees the first allocation?

3. At L3, the function `name.push_str(" Jr.")` resizes the string's heap allocation. This does three things. First, it frees the original heap memory. Second, it creates a new larger allocation. Third, it writes "Ferris Jr." into the new allocation. `first` now points to deallocated memory.

Besides, isn't the exact behaviour an implementation detail of String?

"Pointee" used incorrectly to refer to the variable doing the pointing

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:

    • pointee
  • I have checked the latest main branch to see if this has already been fixed, in this file:

    • src/ch4 files (although these don't seem to include the diagrams where the problem is, couldn't figure out what code produces the diagrams)

URL to the section(s) of the book with this problem:

Description of the problem:

I believe there has been an error of thinking the word pointee refers to the variable doing the pointing (subject), rather than the thing being pointed to (object). In chapter 4, the sentence "undefined behavior: pointer used after its pointee is freed" is used in multiple of the diagrams showing how values/pointers in the stack and heap change. However, in some of the diagrams it is not the pointee (the data on the heap) that has been freed, but a variable pointing to the data.

example

Wiktionary's definition of pointee.

Suggested fix:
Change "undefined behavior: pointer used after its pointee is freed" to "undefined behavior: pointer used after it has been freed" or "undefined behavior: pointer used after the pointing variable has been freed" in diagrams where the pointer is freed and the heap data remains.

[Suggestion] Extracting quizzes

How about extracting all the quizzes? I feel the quizzes are of great quality, but what makes it inconvenient is that they are mixed with the book.

I have read Rust book, but in my first language not English. And there may be many newbies similar to me.

Translation is unnecessary at first. Because newbies may just be unfamiliar with English but still be able to read English, especially while quizzes are short.

Add a note on shadowing to chapter 4?

Maybe it is worth adding a note on shadowing somewhere in chapter 4.

Specifically, that when you are shadowing a variable with heap data, the old variable still exists in memory but is inaccessible.

fn main() {
let s = String::from("Hello");
let s_ref = &s;
let s = String::from("world");
println!("{s_ref}"); //prints Hello 
}

I think it worth mentioning with regards to ownership rules. In particular that the Box heap data is not deallocated when s is shadowed but rather at the end of the function.

fn main() {
let s = Box::new(2);
let s = String::from("hello"); 
// the old instance of s which is Box::new(2) is **still** in memory but inaccessible.
// It will be dropped according to the normal ownership rules. 
//That is when the scope ends the heap data of the Box
// will be deallocated as its owner (the old instance of s) goes out of scope.
}

Confusion of "type" and "value'

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch19-04-advanced-types.html#the-never-type-that-never-returns

Description of the problem:

Rust has a special type named ! that’s known in type theory lingo as the empty type because it has no values.

Later it says:

As you might have guessed, continue has a ! value. That is, when Rust computes the type of guess, it looks at both match arms, the former with a value of u32 and the latter with a ! value.

Here, the loop never ends, so ! is the value of the expression.

How can ! be the value of something if it's a type that has no values?

Suggested fix:

Replace "value" with "type" where appropriate.

Link to the original Chapter 4

Please consider referring less experienced or knowledgeable readers to the original version of Chapter 4. The rewritten text is substantially more challenging and will not be appropriate for many readers. It is not particularly well suited as a drop-in replacement for the majority of students. The original Chapter 4 should be considered a prerequisite to the rewritten chapter.

[Feature Idea] Export Highlights

Hello all!

I have been reading through the book and greatly enjoying it.

One idea I had was a way to export the highlighted portions as well as the notes, whether to a .txt or .csv file. I think that this would be incredibly helpful, especially due to the ephemeral nature of the highlights/notes (deleted when cookies are cleared).

Please let me know if this is a worthwhile idea -- I would be happy to assist in implementing it if so.

Thanks!

on "Understanding Ownership"

  • 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:

https://rust-book.cs.brown.edu/ch04-01-what-is-ownership.html

Description of the problem:

the last quiz, question 4. it says this is NOT undefined behaviour:

let b = Box::new(0);
let b2 = b;
println!("{}", b);
move_a_box(b2);

why? "b" is assigned and then used at a function call to println. therefore, "b" already looses ownership.

also, in a smartphone, quiz #4 submit button is not showing.

Suggested fix:

Highlight feature not working on Firefox

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • highlight
    • firefox
  • I have checked the latest main branch to see if this has already been fixed, in this file:
    • checked the online version

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/

Description of the problem:

When trying to highlight text in Firefox (as indicated in the first page "Try highlighting this text"), on Firefox, the note popup comes up, but it gets stuck on submitting it. It does not close the popup, nor does it highlight the text. The popup can be closed by clicking outside of it, but this again does not highlight the text.

I have checked that highlighting works on Chromium, thus the issue is likely related to Firefox

User-Agent | Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/114.0

Suggested fix:

Without debugging, I am not sure of a fix. Perhaps a JS compatibility issue with Firefox may have caused it.

Warn about the resource usage of the Ownership Inventory more clearly

The article already warns that:

Each instance of the IDE appears to take around ~300 MB.

But I don't think this warning is dire enough as to how much memory it's going to actually consume. This is how much memory it ended up consuming in the quiz result view (on Firefox).

2023-06-27T17:41:04
It completely froze my 4GB RAM potato when I did the quiz. I recently upgraded to 16GB and even then it struggled (it started swapping even though I'm not running anything but the browser).

mdbook build failed due to the "aquascope" preprocessor failure

  • [ X] I have checked the latest main branch to see if this has already been fixed
  • [ X] I have searched existing issues and pull requests for duplicates

When I run mdbook build I met this information:
PS D:\code\rustworks\rustbook> mdbook build 2023-03-11 14:11:16 [INFO] (mdbook::book): Book building has started Warning: The aquascope plugin was built against version 0.4.28 of mdbook, but we're being called from version 0.4.25 Command failed 2023-03-11 14:11:16 [ERROR] (mdbook::utils): Error: The "aquascope" preprocessor exited unsuccessfully with exit code: 1 status

The vers:
PS D:\code\rustworks\rustbook> mdbook -V
mdbook v0.4.25
PS D:\code\rustworks\rustbook> mdbook-aquascope -V
mdbook-preprocessor-utils 0.1.4

Pls fix it, or let me know how to debug it. Thanks and BRs!

Link to a non-existent section in Chapter 4

  • 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

URL to the section(s) of the book with this problem:
Clone and Copy for Duplicating Values

Description of the problem:
Chapter 4 between this and the official book are vastly different. The fourth paragraph links the Stack-Only Data: Copy section in Chapter 4. But this doesn't have that section.

Suggested fix:
I can't seem to find the equivalent of that section here, but if there is, the link should point to that. If not, add the section.

Presenting shadowing as a problem in the context of match guards is confusing

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch18-03-pattern-syntax.html#extra-conditionals-with-match-guards

Description of the problem:

In Listing 18-11, we mentioned that we could use match guards to solve our pattern-shadowing problem. Recall that we created a new variable inside the pattern in the match expression instead of using the variable outside the match. That new variable meant we couldn’t test against the value of the outer variable. Listing 18-27 shows how we can use a match guard to fix this problem.

But using a match guard doesn't fix this problem, using another name (n) does - and it would even without a match guard, for example:

fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(n) => {
            if n == y {
                println!("Matched, n = {}", n);
            } else {
                println!("Default case, x = {:?}", x);
            }
        },
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {}", x, y);
}

Suggested fix:

Remove the implication that shadowing is the problem that using a match guard solves.

Question 2 in 6.4 has incorrect / confusing answers

  • 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

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch06-04-inventory.html#the-quiz

Description of the problem:

Every time you invoke the make_separator function with an empty string you invoke undefined behavior, even if you don't actually print / use the return value.

Playground

fn make_separator(user_str: &str) -> &str {
    if user_str == "" {
        let default = "=".repeat(10);
        unsafe { &*std::ptr::addr_of!(default) }
    } else {
        user_str
    }
}

fn main() {
    make_separator("");
}

Miri Output:

error: Undefined Behavior: constructing invalid value: encountered a dangling reference (use-after-free)
  --> src/main.rs:11:5
   |
11 |     make_separator("");
   |     ^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free)
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
   = note: BACKTRACE:
   = note: inside `main` at src/main.rs:11:5: 11:23

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

Suggested fix:

While the question is good for figuring out if the learner properly learned about dangling references to locals, it's distracting to differentiate between instant and late Undefined Behavior. It's probably best for these confusing answers to be removed.

Side notes:

Both this and question 5 have this passage:

Which (if any) of the following programs would (1) pass the compiler

which is also really confusing considering that the whole question is under the assumption that the:

compiler did NOT reject this function

Additionally I find it weird that we have to imagine an imaginary compiler where the code is not rejected, as it's really unclear how similar this imaginary compiler even is to the real compiler. Technically such an imaginary compiler could make this whole function not be Undefined Behavior / cause any memory violations. It honestly would be better to remove this whole confusing phrasing and just use the actual unsafe code that makes the code compile. Then no imaginary compiler is necessary, just the real compiler with all the behavior being in tact.

Opera GX Chapter 4.1 memory leak

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch04-01-what-is-ownership.html

Description of the problem:
Once I open the page in opera GX, my memory usage from the thread controlling the tab on which the site is open starts hogging memory progressively. I can scroll but just a part of the page loads. The scroll bar stays static. I have turned my extensions on and off, confirming they aren't the problem. The bug isn't happening in chrome, I haven't tried on a fresh install of the browser. Eventually it comes to multiple gigs of usage and gets nuked by Opera.

Suggested fix:
¯\(ツ)

Wrong function in code example in section 4.5

  • 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

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch04-05-ownership-recap.html

Description of the problem:

In the 4th code example, the function make_document is called, but it is not defined in the example nor in previous ones.

Suggested fix:
Replace with new_document, function that is defined in previous code block, and seem to work fine, and it seems that were the original intention.

`Context` for Quiz `Question 3` in Section 2 of Chapter 13 has a typo

  • 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:
    • quizzes/ch13-02-iterators.toml

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch13-02-iterators.html#using-closures-that-capture-their-environment

Description of the problem: The Context for Question 3 has typo.

Therefore the closure in map takes &i32 as input. The multiplication operator * is implemented for &i32, so x does not need to be dereferences in x * 2.

Suggested fix: Change the above sentence like so.

Therefore the closure in map takes &i32 as input. The multiplication operator * is implemented for &i32, so x does not need to be dereferenced in x * 2.

Instructions on how build the project listed in README is incomplete

The only step mentioned in README is to installing mdbook at the rust-lang/rust version as advised, but running mdbook build shows up missing aquascope and quiz commands (and ultimately failed for I'm not sure if related reasons?).

2023-08-24 10:23:08 [INFO] (mdbook::book): Book building has started
2023-08-24 10:23:08 [WARN] (mdbook::preprocess::cmd): The command wasn't found, is the "aquascope" preprocessor installed?
2023-08-24 10:23:08 [WARN] (mdbook::preprocess::cmd):   Command: mdbook-aquascope
2023-08-24 10:23:08 [WARN] (mdbook::preprocess::cmd): The command wasn't found, is the "quiz" preprocessor installed?
2023-08-24 10:23:08 [WARN] (mdbook::preprocess::cmd):   Command: mdbook-quiz
2023-08-24 10:23:08 [INFO] (mdbook::book): Running the html backend
2023-08-24 10:23:08 [ERROR] (mdbook::utils): Error: Rendering failed
2023-08-24 10:23:08 [ERROR] (mdbook::utils):    Caused By: Unable to copy across additional CSS and JS
2023-08-24 10:23:08 [ERROR] (mdbook::utils):    Caused By: Unable to copy /Users/atsuzaki/projects/rust-book/js-extensions/packages/consent-form/dist/index.css to /Users/atsuzaki/projects/rust-book/book/js-extensions/packages/consent-form/dist/index.css
2023-08-24 10:23:08 [ERROR] (mdbook::utils):    Caused By: No such file or directory (os error 2)

I tried to cargo install mdbook-aquascope and cargo install mdbook-quiz, then proceeded to run into trouble where the aquascope is built with a diff version, and subsequently dies.

2023-08-24 10:21:21 [INFO] (mdbook::book): Book building has started
Warning: The aquascope plugin was built against version 0.4.34 of mdbook, but we're being called from version 0.4.28
Command failed
2023-08-24 10:21:21 [ERROR] (mdbook::utils): Error: The "aquascope" preprocessor exited unsuccessfully with exit status: 1 status

I reckon the correct thing to do is to not use the crates.io ver, but directly from the aquascope repo?

But alas, would really appreciate if we could have clearer build instructions for this project. (I want to help fix your bugs, if only I could build this darn thing 😭)

Build instructions seem to be incomplete

Running mdbook build is not enough, as I get this error message:

2023-02-08 23:41:04 [INFO] (mdbook::book): Book building has started
2023-02-08 23:41:04 [WARN] (mdbook::preprocess::cmd): The command wasn't found, is the "quiz" preprocessor installed?
2023-02-08 23:41:04 [WARN] (mdbook::preprocess::cmd):   Command: mdbook-quiz
2023-02-08 23:41:04 [INFO] (mdbook::book): Running the html backend
2023-02-08 23:41:05 [ERROR] (mdbook::utils): Error: Rendering failed
2023-02-08 23:41:05 [ERROR] (mdbook::utils):    Caused By: Unable to copy across additional CSS and JS
2023-02-08 23:41:05 [ERROR] (mdbook::utils):    Caused By: Unable to copy C:\sync\rust-book\js-extensions/packages/consent-form/dist/index.css to C:\sync\rust-book\book\js-extensions/packages/consent-form/dist/index.css
2023-02-08 23:41:05 [ERROR] (mdbook::utils):    Caused By: The system cannot find the path specified. (os error 3)

I tried running npm install into js-extensions, and also downloaded pnpm and tried running that, but I get this error with pnpm build:

packages/telemetry build$ node build.mjs
│ Error: spawn tsc ENOENT
│     at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19)
│     at onErrorNT (node:internal/child_process:476:16)
│     at processTicksAndRejections (node:internal/process/task_queues:82:21) {
│   errno: -4058,
│   syscall: 'spawn tsc',
│   path: 'tsc',
│   spawnargs: [ '-emitDeclarationOnly' ]
│ }
└─ Failed in 444ms at C:\sync\rust-book\js-extensions\packages\telemetry
packages/consent-form build$ node build.mjs
└─ Running...
C:\sync\rust-book\js-extensions\packages\telemetry:
 ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  [email protected] build: `node build.mjs`
Exit status 1
 ELIFECYCLE  Command failed with exit code 1.

What is the correct way of building this book?

5.1 Misleading description of what happens when Creating Instances from Other Instances

The sentence here describing what happens to user1 after it's used to created user2 is inaccurate:

In this example, we can no longer use user1 after creating user2 because the String in the username field of user1 was moved into user2

This suggests that the entire user1 struct is now unusable, but it is not:

let user1 = User {
    email: String::from("[email protected]"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};

let user2 = User {
    email: String::from("[email protected]"),
    ..user1
};

println!("{} {}", user1.active, user1.email); // user1 is still usable

playground

I think a better description would be:

In this example, we can no longer use user1.username after creating user2 because the String in the username field of user1 was moved into user2

Quiz in 18.1 uses `..` remaining parts ignore syntax before it's explained

  • [ ✅ ] 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

URL to the section(s) of the book with this problem:

`_` or `..`, as you’ll see in the [“Ignoring Values in a

Description of the problem:

Section 18.1 on pattern matching mentions that .. could be used to ignore values:

To fix the error, we could ignore one or more of the values in the tuple using _ or .., as you’ll see in the “Ignoring Values in a Pattern” section. If the problem is that we have too many variables in the pattern, the solution is to make the types match by removing variables so the number of variables equals the number of elements in the tuple.

and the quiz at the end of the section quizzes you on the .. match-ignoring syntax:

but the .. syntax is not explained until section 18.3:

#### Ignoring Remaining Parts of a Value with `..`

Suggested fix:

Move the quiz on .. to after section 18.3, or move the explanation of .. into section 18.1.

Use of MutexGuard in match expressiond prevents threads from running in parallel

  • 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

URL to the section(s) of the book with this problem:

match receiver.lock().unwrap().recv() {

Description of the problem:

As the book warns just in the section prior to the one linked above, using a MutexGuard in a match expression prevents mutex from being unlocked and the threads from running in parallel.

Suggested fix:

+            let message = receiver.lock().unwrap().recv();
+
-            match receiver.lock().unwrap().recv() { 
+            match message {

Quiz in 19.1 talks about unsafe allowing values to be uninitialized, but 19.1 doesn't teach that

  • [ ✅ ] 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

URL to the section(s) of the book with this problem:

Allowing values to be uninitialized is reasonable because the borrow checker adopts a conservative policy that values must always initialized, but it's sometimes useful to work with uninitialized values. See [`MaybeUninit`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html) and the [`take_mut`](https://docs.rs/take_mut/0.2.2/take_mut/index.html) crate.

Description of the problem:

The quiz in section 19.1 says it's reasonable to use unsafe to allow values to be uninitialized, but section 19.1 doesn't talk about that anywhere.

Suggested fix:

Update section 19.1 of the book to talk about using unsafe to allow values to be uninitialized, or remove this from the quiz.

Text highlighting color in dark mode.

  • 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

URL to the section(s) of the book with this problem:

Description of the problem:
When highlighting some piece of text while in dark themes (i'm actually using the navy theme) it uses a bright yellow color that makes the text hard to read.
I'm using Firefox while using the book.

Suggested fix:
Use some color for highlighting in dark themes that gives more contrast between the text and the highlighting itself.

404 rust-book.cs.brown.edu

  • 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

URL to the section(s) of the book with this problem:

Description of the problem:
I not sure if this is an intermittent issue or some network issue. But the https://rust-book.cs.brown.edu/ shows 404.
Suggested fix:

Guessing Game (chapter 2) suggestion

Why not just declare guess once, like this:

    let mut guess;
    loop {
        guess = String::new();

instead of what's presented:

    loop {
        let mut guess = String::new();

Quizzes that are written using WASM causes the website to crash

The problem is:
Whenever I have to re-take a quiz, My PC temperature increases and my fan start spinning. On top of that, the website crashes and I have to reload it. Even after reloading the website and pressing "retry the quiz", the same problem starts again.

I think it's because some weird loop is running in the background when re-taking quizzes or something like that. I hope this will be fixed.

Listing 15-25. The code defines and imports List enum simultaneously

  • 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:

Description of the problem:

Suggested fix:

Bad phrasing

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch17-03-oo-design-patterns.html#trade-offs-of-the-state-pattern

Description of the problem:

If we were to create an alternative implementation that didn’t use the state pattern, we might instead use match expressions in the methods on Post or even in the main code that checks the state of the post and changes behavior in those places.

The only valid subject for "checks" and "changes" is "the main code", but then it's unclear how we would use match expressions in the methods on Post and what "those places" refers to.

Suggested fix:

Change to "check" and "change"?

Confusing syntax `(self.postprocess)(n)`

URL to the section with problem: Ch13, last quiz, last question

Description of the problem:

impl<F: ___(i32) -> i32> Analyzer<F> {
    //...
    pub fn pipeline(&self, n: i32) -> i32 {
        // ...
        (self.postprocess)(n)
    }
}

That last return was surprising for me, why you put self.postprocess in brackets. I thought it's a bug. I tried without brackets and get very helpful error, but still. I think this should be explained before the quiz.

Also this placeholder ___(i32) was very confusing for me. My first thoughts was like "wtf?! I skip some chapter where this syntax explained?" I closed quiz, scrolled around current chapter. Open quiz again. Next thought "Maybe it's like that underscore don't care argument, but why there three underscores and not one?!" And only when I looked on answer options I understand this "syntax" means.

As a fix for placeholder maybe use emoji? like

impl<F:(i32) -> i32> Analyzer<F> {

Ch 2: Incorrect wording on type conversion explanation

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch02-00-guessing-game-tutorial.html

Description of the problem:
Reading this sentence it does not make a lot of sense, I believe that the word "compare" is incorrect here

The trim method on a String instance will eliminate any whitespace at the beginning and end, which we must do to be able to compare the string to the u32, which can only contain numerical data.

Suggested fix:

The trim method on a String instance will eliminate any whitespace at the beginning and end, which we must do to be able to convert the string to the u32 type, which can only contain numerical data.

Continue outside a loop while handling invalid input

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch02-00-guessing-game-tutorial.html#handling-invalid-input

Description of the problem:

The following code:

let mut guess = String::new();

// --snip--

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,
};

Throws the error below on rustc 1.67.1 (d5a82bbd2 2023-02-07)

`continue` outside of a loop
cannot `continue` outside of a loop (rustc E0268)
─────────────────────────────────────────────────────────────────
https://doc.rust-lang.org/error-index.html#E0268

Sometimes text highlighting extends to the bottom of the page when reloading.

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • highlight
    • invalid
    • broken
  • I have checked the latest main branch to see if this has already been fixed, in this file:

Description of the problem:

Sometimes when highlighting text and reloading the page, the target text is no longer highlighted but instead all text following it is highlighted to the end.

I don't have a clear individual replication path, but I copied my highlights from the localStorage to Chrome, Firefox and Edge and in all of them the same error happened.

By having the highlights and visiting the following sections:

The pages look like this:
image

And the following error appears in the console:
image

Suggested fix:

I have identified that the error occurs within the highlightIsValid function of the utils.ts file on line 67, where the innerHTML of the first element of the dom_nodes array is readed but this array is empty because the validation of line 64 uses the statement if (!dom_nodes) return false; which only validates that it is not falsy but not its length.

Therefore it should be corrected by replacing this validation with:

export const highlightIsValid = (highlighter: Highlighter, highlight: HighlightSource) => {
  /*other code*/

  // if highlight has no DOM node, filter
  if (!dom_node?.length) return false;
};

Highlighting text does not work

  • 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

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ (first highlight test)

Description of the problem: Highlighting doesn't work

Whenever I press "Submit" in the highlight input box, with or without having entered text, nothing happens (box doesn't even close) and the following appears in my console:
image

Obfuscated JS probably isn't that useful, but here is where my debugger thinks the issue is:
image

System details:
OS: Linux Mint XFCE 21.1
Browser: Firefox 108.0.2

Let me know if more information is required :)

Diagrams in 4.1 describe code that causes fatal stack overflow without warning/ferris

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch04-01-what-is-ownership.html

Description of the problem:
In the section "Boxes Live in the Heap", the diagrams show a code snippet:

let a = [0; 1_000_000];
let b = a;

and later

let a = Box::new([0; 1_000_000]);
let b = a;

which is also talked about much more in the chapter. This code causes a stack overflow for both the stack-based array version and box-based heap version because the rust compiler actually copies a stack based array and moves it into the heap (https://doc.rust-lang.org/beta/alloc/boxed/index.html#examples). There is no warning about this or Ferris image to indicate to the reader that this code doesn't actually work, and since neither the compiler nor rust-analyzer warns about this either, I think it would be beneficial to include it in the chapter itself.

Suggested fix:
Either add a Ferris image for "This code panics!", write a "Note:" section explaining this, or change the values in the array to be under the smallest default stack size across operating systems (512kib on mac iirc). I understand this is kind of a nit-picky issue but new readers who are following the book interactively and are met with a runtime error will be very confused.

Wrong example of iteration over a vector

  • 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

URL to the section(s) of the book with this problem:

https://rust-book.cs.brown.edu/ch08-01-vectors.html

Description of the problem:

Listing 8-7 has the following code:

let v = vec![100, 32, 57];
for n_ref in &v {
    // n_ref has type &i32
    let n_plus_one: i32 = *n_ref + 1;
    println!("{}", n_plus_one);
}

It says that the deference operator is necessary to get the value in n_ref before we can add 1 to it. Dereferencing isn't necessary as we don't iterate over mutable references.

Suggested fix:

Just print the number because Listing 8-8 already depicts this example.

A feature idea - a quiz that allows the users to specify permissions for variables/objects/parameters etc.

The permission, stack, and heap diagrams, as well as the aquascope and all the quizzes, have been very helpful. Here's my idea: how would everyone feel about a quiz that allows the user to click on any point within the code and then specify the permissions of the variables? After clicking submit, the aquascope runs and checks if you got it right.

For example, suppose that a quiz is:

  • Click L1 box and type? or select? permissions for v.
  • Click L2 box and type/select permissions for v, n, *n.
  • Click L3 ..
  • ..

image

Maybe the user can click the symbol column (where ⮥ is located) to cycle through either ⮧, ->, ⟲, ♺.

They can click the permissions columns to cycle through symbols like +R, +W, +O.

For the expected permissions, maybe something similar like clicking to cycle through R,W,F.

image

The full code is inconsistent with the listings

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch20-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs

Description of the problem:

For instance, the handle_connection function in src/main.rs has let mut buffer = [0; 1024]; as the first line instead of using BufReader.

Suggested fix:

Update the full code to match the listings.

Confusing use of the word "path" in ch04-02

  • 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

URL to the section(s) of the book with this problem:
https://github.com/cognitive-engineering-lab/rust-book/blob/main/src/ch04-02-references-and-borrowing.md

Description of the problem:
The word "path" is used extensively in the "references and borrowing" section in chapter 4 to seemingly reference the concept of a "place" in Rust ("lvalue" in C++) AKA an addressable value. The use of the word in this way is bound to cause confusion with readers of the book when speaking about these "paths" outside and inside the context of the book; the word "path" in Rust is generally used to refer to module paths or file system paths, and the book later uses them to refer to module paths.

Suggested fix:
Replace the word "path" with the more accurate and clear word "place".

Possible error on Chapter 4.3

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • Chapter 4
  • 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:
https://rust-book.cs.brown.edu/ch04-03-fixing-ownership-errors.html#fixing-an-unsafe-program-copying-vs-moving-out-of-a-collection

Description of the problem:
v should not lose read permission in second line.

Suggested fix:
v should keep its read permission.

Comma missing in Chapter 3.2 sentence

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch03-02-data-types.html

Description of the problem:
In the sentence "Every value in Rust is of a certain data type, which tells Rust what kind of data is being specified so it knows how to work with that data. We’ll look at two data type subsets: scalar and compound.", there is a missing comma after "data is being specified". I think it will make the sentence more readable.

Suggested fix:
Add a comma after "data is being specified" and before "so it knows how to work with that data".

Thanks. I am just learning Rust and Git at the same time.

Bad phrasing

  • 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

URL to the section(s) of the book with this problem:
https://rust-book.cs.brown.edu/ch20-02-multithreaded.html#sending-requests-to-threads-via-channels

Description of the problem:

We want the Worker structs that we just created to fetch the code to run from a queue held in the ThreadPool and send that code to its thread to run.

What's the antecedent of "its"? "Worker structs" is plural.

Suggested fix:

Replace "Worker structs" with "each Worker struct" or "its thread" with "their threads".

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.