Problem when `cargo test`

There is one warning in this test:
warning: function show_char is never used

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

fn show_char(a_char: char) {
    if a_char == 'A' {
        println!("/////{}/////", a_char);
    } else {
        panic!("======={}======", a_char);
    }
}

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

    #[test]
    fn will_ok() {
        show_char('A');
    }

    // #[ignore]
    #[test]
    fn will_err() {
        show_char('a');
    }
}

output:

warning: function `show_char` is never used
 --> src\lib.rs:5:4
  |
5 | fn show_char(a_char: char) {
  |    ^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: `lib-sample01` (lib) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src\lib.rs (target\debug\deps\lib_sample01-db19219f39bd4e4a.exe)

running 2 tests
test tests::will_err ... FAILED
test tests::will_ok ... ok

failures:

---- tests::will_err stdout ----
thread 'tests::will_err' panicked at src\lib.rs:9:9:
=======a======
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::will_err

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

but it's no warning when i use pub fn show_char instead of fn show_char.

what is the reason for this?

cargo --version : cargo 1.75.0 (1d8b05cdd 2023-11-20)

1 Like

When your library is compiled normally, without tests, nothing calls show_char(), and nothing can call show_char(), so there is a warning that the code is useless.

The cargo test command happens to include a normal build too. The warning is not about the tests.

4 Likes

Because nothing can call show_char() without a pub, like pub fn add() with no warning?

I am confused about there is no warning with a pub, because pub fn add has no warning when it's unused.

The pub fn may be used by another crate compiled later, since it's public. That other crate might even be written by someone else, later, after looking at what your library offers, so the compiler can't know now whether add will be used later or not.

The intent of dead_code warnings is to identify code that could (hypothetically) be deleted without changing the functionality of the crate. Public items being deleted would be such a change, so they never get dead_code warnings.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.