Seemingly invalid unused import warning

I have the following code:

pub fn gcd(a: u64, b: u64) -> Result<u64, String> {
    Ok(a + b)
}

mod tests {
    use gcd;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(6, 14), Ok(20));
    }
}

When I run this using cargo test, I get the following warning:

warning: unused import: `gcd`
 --> src/lib.rs:7:9
  |
7 |     use gcd;
  |         ^^^
  |
  = note: #[warn(unused_imports)] on by default

If I remove use gcd; line from tests module, I get the expected error:

error[E0425]: cannot find function `gcd` in this scope
 --> src/lib.rs:9:20
  |
9 |         assert_eq!(gcd(6, 14), Ok(20));
  |                    ^^^ not found in this scope
help: possible candidate is found in another module, you can import it into scope
  |
1 | use gcd;
  |

So, is the unused import warning a bug or am I missing something here?

cargo test compiles the library twice, a regular and a test version. The warning comes from the regular one. The solution would be to gate the test module (or just the use) so it’s only complied in a test build.

#[cfg(test)]
mod tests { ... }
5 Likes

I see. Thanks :slight_smile: for clarifying.