cognitive-engineering-lab / rust-book

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

Section 3.1 Shadowing Quiz Question 1 #219

Open jgnoonan opened 3 weeks ago

jgnoonan commented 3 weeks ago

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch03-01-variables-and-mutability.html#shadowing

Description of the problem: According to the answer for question 1, the following code should compile:

fn main() { let mut x: u32 = 1; { let mut x = x; x += 2; } println!("{x}"); }

On my system using VSCode with Rust-Analyzer, it does not compile with the following errors:

variables % cargo build Compiling variables v0.1.0 (/Users/jgnoonan/rustbook/variables) warning: value assigned to x is never read --> src/main.rs:6:5 6 x += 2; ^

= help: maybe it is overwritten before being read? = note: #[warn(unused_assignments)] on by default

warning: variable does not need to be mutable --> src/main.rs:3:9 3 let mut x: u32 = 1; ----^
help: remove this mut

= note: #[warn(unused_mut)] on by default

warning: variables (bin "variables") generated 2 warnings (run cargo fix --bin "variables" to apply 1 suggestion) Finished dev profile [unoptimized + debuginfo] target(s) in 0.14s

Suggested fix: There should be a list of defaults that must be changed for the code to compile.

cheyenneson commented 3 weeks ago

It looks like this still compiles with no errors, but the messages you are seeing are simply warnings. The first warning is that x is never used, which would be fixed by printing x after line 5 but might distract from the original intention of what the question is trying to teach. The second is saying that the original declared value x does not need to be mutable, which is true but also removes what I think was the original point of the question. Technically this question is still correct since this does compile (your compiler should have still produced a main binary file on your machine with this output). To prevent confusion, the question could specify that you can ignore warnings, but warnings themselves don't mean that it failed to compile.