如何抑制“函数从不使用"测试使用的函数的警告? [英] How to suppress "function is never used" warning for a function used by tests?
问题描述
我正在用 Rust 编写一个程序,我对它进行了一些测试.我为这些测试编写了一个辅助函数,但是每当我使用 cargo build
进行构建时,它都会警告我从未使用过该函数:
warning: function is never used: ... #[warn(dead_code)] 默认开启
如何将此函数标记为已使用以免收到警告?
具体问题
<块引用>如何将此函数标记为已使用以免收到警告?
Rust 编译器运行许多 lint 以警告您代码中可能存在的问题dead_code
lint 就是其中之一.在代码完成时指出错误非常有用,但在早期阶段也可能会造成麻烦.通常,这可以通过删除未使用的代码或标记公共方法来解决.但是,所有 lint 都可以通过 allow
关闭它们,并且您的错误消息(#[warn(dead_code)] 默认开启
)包含您使用的 lint 的名称可以禁用.
#[allow(dead_code)]fn my_unused_function() {}
替代测试
<块引用>我为这些测试编写了一个辅助函数,但是每当我使用 cargo build
进行构建时,它都会警告我从未使用过该函数.
这恰好是一种特殊情况,即仅用于测试的代码在真正的可执行文件中不需要,并且可能不应该包含在内.
为了选择性地禁用测试代码的编译,您可以使用 cfg
属性与 test
配置文件.
#[cfg(test)]fn my_test_specific_function() {}
以这种方式标记时,编译器知道在编译期间忽略该方法.这类似于 C 或 C++ 等其他语言中常用的 ifdef
用法,您告诉预处理器忽略封闭的代码,除非定义了 TESTING
.
#ifdef TESTING...#万一
I'm writing a program in Rust and I have some tests for it. I wrote a helper function for these tests, but whenever I build using cargo build
it warns me that the function is never used:
warning: function is never used: ... #[warn(dead_code)] on by default
How I can mark this function as used so as not to get the warnings?
Specific question
How I can mark this function as used so as not to get the warnings?
The Rust compiler runs many lints to warn you about possible issues in your code and the dead_code
lint is one of them. It can be very useful in pointing out mistakes when code is complete, but may also be a nuisance at earlier stages. Often, this can be solved by either deleting unused code, or by marking a public method. However, all lints can be turned off by allow
ing them, and your error message (#[warn(dead_code)] on by default
) contains the name of the lint you could disable.
#[allow(dead_code)]
fn my_unused_function() {}
Alternative for testing
I wrote a helper function for these tests, but whenever I build using
cargo build
it warns me that the function is never used.
This happens to be a special case, which is that code that is only used for testing isn't needed in the real executable and should probably not be included.
In order to optionally disable compilation of test code, you can mark it accordingly using the cfg
attribute with the test
profile.
#[cfg(test)]
fn my_test_specific_function() {}
When marked in this way, the compiler knows to ignore the method during compilation. This is similar to commonly used ifdef
usage in other languages like C or C++, where you are telling a preprocessor to ignore the enclosed code unless TESTING
is defined.
#ifdef TESTING
...
#endif
这篇关于如何抑制“函数从不使用"测试使用的函数的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!