[英]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.我是 Rust 的新手,我想知道以下代码在运行前产生的警告。 I am running version: rustc 1.67.0 (fc594f156 2023-01-24) from the stable channel.我正在运行版本:来自稳定频道的 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 }
$
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.我认为第 9 行中帐户结构的调试打印会读取余额字段。
Does it have something to do with at what point in the compilation of the code that the println?它与 println 在代码编译中的哪个点有关吗? macro is expanded vs when the lint check for dead code occurs?宏被扩展 vs 何时发生死代码的 lint 检查?
All things I tried that 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.派生的Debug
实例是dead_code
警告的一种特殊情况,如果您的代码仅在Debug
实现中使用一个字段,那么它仍将认为它未使用,即该字段未在非调试代码中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.