如何在 Rust 中消除单个语句的警告? [英] How to quiet a warning for a single statement in Rust?

查看:280
本文介绍了如何在 Rust 中消除单个语句的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个警告,例如 path_statementsunused_variables.有没有办法忽略这一瞬间,而不将它们隔离到代码块或函数中?

Say there is a single warning such as path_statements, unused_variables. Is there a way to ignore a single instant of this, without isolating them into a code block or function?

要清楚,当代码中有一个警告时.我希望能够仅消除该警告,而不必针对特定警告进行特殊更改.并且在其他任何地方都没有这种安静的警告,甚至稍后在同一功能中也是如此.

To be clear, when there is a single warning in the code. I would like the ability to quiet only that warning, without having to do special changes addressing the particular warning. And without this quieting warnings anywhere else, even later on in the same function.

使用 GCC,可以按如下方式完成:

With GCC this can be done as follows:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
    /* Isolated region which doesn't raise warnings! */
    this_would_raise_Wformat(args);
#pragma GCC diagnostic pop

Rust 是否具有同等功能?

Does Rust have the equivalent capability?

注意,我在询问如何消除警告的一般情况.我知道有一些方法可以解决例如未使用的 var 警告.

Note, am asking about the general case of how to quiet warnings. Am aware there are ways to resolve unused var warning for eg.

推荐答案

要使警告静音,您必须allow(warning_type) 属性添加到受影响的表达式或任何它的父母.如果您想对某个特定表达式的警告静音,您可以将属性添加到该表达式/语句中:

To silence warnings you have to add the allow(warning_type) attribute to the affected expression or any of its parents. If you only want to silence the warning on one specific expression, you can add the attribute to that expression/statement:

fn main() {
    #[allow(unused_variables)]
    let not_used = 27;

    #[allow(path_statements)]
    std::io::stdin;

    println!("hi!");
}

然而,为语句/表达式(相对于项,如函数)添加属性的功能仍然有点破.特别是,在上面的代码中,std::io::stdin 行仍然会触发警告.您可以在此处阅读有关此功能的正在进行的讨论.

However, the feature of adding attributes to statements/expressions (as opposed to items, like functions) is still a bit broken. In particular, in the above code, the std::io::stdin line still triggers a warning. You can read the ongoing discussion about this feature here.

通常不需要使用属性.许多警告(例如 unused_variablesunused_must_use)可以通过使用 let _ = 作为您的左侧陈述.一般来说,任何以下划线开头的变量都不会触发未使用的警告.

Often it is not necessary to use an attribute though. Many warnings (like unused_variables and unused_must_use) can be silenced by using let _ = as the left side of your statement. In general, any variable that starts with an underscore won't trigger unused-warnings.

这篇关于如何在 Rust 中消除单个语句的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆