PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

[FIXED] Why is rust complaining about an unused function when it is only used from tests?

 April 27, 2022     dead-code, rust, warnings     No comments   

Issue

When a function is only called from tests rust complains that it is never used. Why does this happen and how to fix this?

Example:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=52d8368dc5f30cf6e16184fcbdc372dc

fn greet() {
    println!("Hello!")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_greet() {
        greet();
    }
}

I get the following compiler warning:

   Compiling playground v0.0.1 (/playground)
warning: function is never used: `greet`
 --> src/lib.rs:1:4
  |
1 | fn greet() {
  |    ^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted

Solution

In rust fn is private by default. greet() is not accessible outside your module. If greet() is not used inside it except in tests, then rust is correctly flagging it as dead code.

If greet() is supposed to be part of your public interface mark it as pub:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8a8c50b97fe3f1eb72a01a6252e9bfe6

pub fn greet() {
    println!("Hello!")
}

If greet() is a helper intended to be only used in tests move it inside mod tests:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3dc51a36b4d5403ca655dec0210e4098

#[cfg(test)]
mod tests {
    fn greet() {
        println!("Hello!")
    }
    
    #[test]
    fn test_greet() {
        greet();
    }
}


Answered By - Andrey Bienkowski
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing