You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅禁用Rust结构体单个字段的未使用变量警告

仅禁用结构体特定字段的未使用代码警告

原始代码及警告

代码:

pub struct A {
    a : u64,
    b : bool,
}

pub fn foo() -> u64 {
    let aa = A {
        a: 10,
        b: false
    };
    return aa.a;
}

警告信息:

warning: field `b` is never read
 --> src/lib.rs:3:5
  |
1 | pub struct A {
  |            - field in this struct
2 |     a : u64,
3 |     b : bool,
  |     ^
  |
  = note: `#[warn(dead_code)]` on by default

解决方案:为目标字段添加字段级属性

直接在字段b上方添加#[allow(dead_code)]属性,就能单独禁用该字段的未使用警告,结构体其他现有字段或后续新增字段仍会正常触发未使用检查:

pub struct A {
    a : u64,
    #[allow(dead_code)]
    b : bool,
}

pub fn foo() -> u64 {
    let aa = A {
        a: 10,
        b: false
    };
    return aa.a;
}

说明

  • 该属性是字段专属的,仅对标注的b字段生效,不会影响结构体A的其他成员。
  • 后续若为A新增字段(比如c: String),只要未读取该字段,依然会触发dead_code警告,完全符合需求。

内容的提问来源于stack exchange,提问作者A. K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:05:02