cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
506 stars 82 forks source link

Wrong example of iteration over a vector #81

Open a-gradina opened 1 year ago

a-gradina commented 1 year ago

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.

willcrichton commented 1 year ago

It isn't technically necessary due to the fact that the + operator is overloaded to work on integer references, but I prefer keeping the dereference to make it obvious that n_ref is a pointer and not a primitive value.

a-gradina commented 1 year ago

Then how about changing the text?

_To read the number that n_ref refers to, we have to use the * dereference operator to get to the value in nref before we can add 1 to it, as covered in "Derefencing a Pointer Accesses Its Data".