简体   繁体   中英

dead_code warning in Rust when Debug printing a struct

I am very new to Rust and I am wondering about the warning produced by the following code before it runs. I am running version: rustc 1.67.0 (fc594f156 2023-01-24) from the stable channel.

  1 #[derive(Debug)]
  2 //#[allow(dead_code)]
  3 struct Account {
  4     balance: f32,
  5 }
  6 
  7 fn main() {
  8     let account = Account { balance: 10.0 };
  9     println!("{:?}", account);
 10 }   


$ cargo run
   Compiling bank v0.1.0 (/Users/rlfeider/projects/rust/bank)
warning: field `balance` is never read
 --> src/main.rs:4:5
  |
3 | struct Account {
  |        ------- field in this struct
4 |     balance: f32,
  |     ^^^^^^^
  |
  = note: `Account` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` on by default

warning: `bank` (bin "bank") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.09s
     Running `/Users/rlfeider/projects/rust/bank/target/debug/bank`
Account { balance: 10.0 }
$

Why is a warning printed before the code runs?

I would think that the Debug print of the account struct in line 9 would read the balance field.

Does it have something to do with at what point in the compilation of the code that the println? macro is expanded vs when the lint check for dead code occurs?

All things I tried that gets rid of the warning:

  • Allowing dead_code by uncommenting line 2 removed the warning.
  • explicitly printing account.balance in the println. also gets rid of the warning.
  • Making the account variable mutable and setting account.balance to another value before println. also gets rid of the warning.

The error appears before your program is run because it's a compile time warning.

Derived Debug instances are a special case for the dead_code warning, if your code only uses a field in the Debug implementation then it will still consider it unused, ie the field isn't used in non debugging code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM