繁体   English   中英

调试打印结构时 Rust 中的 dead_code 警告

[英]dead_code warning in Rust when Debug printing a struct

我是 Rust 的新手,我想知道以下代码在运行前产生的警告。 我正在运行版本:来自稳定频道的 rustc 1.67.0 (fc594f156 2023-01-24)。

  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 }
$

为什么在代码运行之前会打印警告?

我认为第 9 行中帐户结构的调试打印会读取余额字段。

它与 println 在代码编译中的哪个点有关吗? 宏被扩展 vs 何时发生死代码的 lint 检查?

我尝试过的所有事情都消除了警告:

  • 通过取消注释第 2 行允许 dead_code 删除了警告。
  • 在 println 中显式打印 account.balance。 也摆脱了警告。
  • 使 account 变量可变并在 println 之前将 account.balance 设置为另一个值。 也摆脱了警告。

该错误在您的程序运行之前出现,因为它是编译时警告。

派生的Debug实例是dead_code警告的一种特殊情况,如果您的代码仅在Debug实现中使用一个字段,那么它仍将认为它未使用,即该字段未在非调试代码中使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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