How to suppress “function is never used” warning for a function used by tests?

后端 未结 3 1023
北恋
北恋 2020-12-29 20:33

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

相关标签:
3条回答
  • 2020-12-29 21:01

    If something is only used in tests, it should be omitted altogether. This can be done with the #[cfg(test)] attribute.

    0 讨论(0)
  • 2020-12-29 21:04

    dead_code is a lint, which means you can allow it on the thing that's causing it to trigger.

    #[allow(dead_code)]
    fn dummy() {}
    
    fn main() {}
    
    0 讨论(0)
  • 2020-12-29 21:07

    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. However, all lints can be turned off by allowing 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
    
    0 讨论(0)
提交回复
热议问题