如何在Rust中禁用未使用的代码警告?

时间:2014-09-16 19:51:46

标签: warnings compiler-warnings rust dead-code

struct SemanticDirection;

fn main() {}
warning: struct is never used: `SemanticDirection`
 --> src/main.rs:1:1
  |
1 | struct SemanticDirection;
  | ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(dead_code)] on by default

我会将这些警告重新发送给任何严肃的事情,但我只是在修补这种语言,而这正在驱使我蝙蝠。

我尝试将#[allow(dead_code)]添加到我的代码中,但这不起作用。

6 个答案:

答案 0 :(得分:220)

你可以

  1. 在结构,模块,函数等上添加allow属性:

    #[allow(dead_code)]
    struct SemanticDirection;
    
  2. 添加crate-level allow attribute;注意!

    #![allow(dead_code)]
    
  3. 将其传递给rustc

    rustc -A dead_code main.rs
    
  4. 通过cargo环境变量

    使用RUSTFLAGS传递它
    RUSTFLAGS="$RUSTFLAGS -A dead_code" cargo build
    

答案 1 :(得分:45)

禁用此警告的另一种方法是在_之前为标识符添加前缀:

struct _UnusedStruct {
    _unused_field: i32,
}

fn main() {
    let _unused_variable = 10;
}

这对于SDL窗口非常有用:

let _window = video_subsystem.window("Rust SDL2 demo", 800, 600);

使用下划线进行前缀不同于使用单独的下划线作为名称。执行以下操作将立即破坏窗口,这不太可能是预期的行为。

let _ = video_subsystem.window("Rust SDL2 demo", 800, 600);

答案 2 :(得分:4)

将代码设为 public 也会停止警告;您还需要公开mod所在的

在编写库时,这很有意义:您的代码在内部是“未使用”的,因为它打算由客户端代码使用。

答案 3 :(得分:3)

另外,铁锈提供了四级绒毛(允许,警告,拒绝,禁止)。

https://doc.rust-lang.org/rustc/lints/levels.html#lint-levels

答案 4 :(得分:1)

您始终可以通过向变量名称添加 (_) 来禁用未使用的变量/函数,如下所示:

let _variable = vec![0; 10];

答案 5 :(得分:0)

对于未使用的函数,您应该将函数公开,但要注意。如果结构不是公开的,那么您仍然会收到如下错误:

//this should be public also
struct A{
   A{}
}

impl A {
    pub fn new() -> A {

    }
}

或者如果你不想公开它,你应该把#[allow(unused)]

相关问题