Search code examples
unit-testingrustdead-code

Rust book unit test example results in dead code warning - why?


While learning Rust and trying out the example unit test related code from the Rust book: https://doc.rust-lang.org/book/ch11-01-writing-tests.html

I get a warning regarding dead code that clearly is being exercised by the unit test. Why is that?

Code in lib.rs

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }
}

Result when running cargo test

$ cargo test
   Compiling adder v0.1.0 (/Users/khorkrak/projects/rust/adder)
warning: associated function is never used: `can_hold`
 --> src/lib.rs:8:8
  |
8 |     fn can_hold(&self, other: &Rectangle) -> bool {
  |        ^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 0.19s
     Running target/debug/deps/adder-1082c4b063a8fbe6

running 1 test
test tests::larger_can_hold_smaller ... ok

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

   Doc-tests adder

running 0 tests

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

$ rustc --version
rustc 1.50.0 (cb75ad5db 2021-02-10)

Solution

  • Changing this

    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    impl Rectangle {
        fn can_hold(&self, other: &Rectangle) -> bool {
            self.width > other.width && self.height > other.height
        }
    }
    

    to this makes the dead code warning go away.

    pub struct Rectangle {
        width: u32,
        height: u32,
    }
    
    impl Rectangle {
        pub fn can_hold(&self, other: &Rectangle) -> bool {
            self.width > other.width && self.height > other.height
        }
    }
    

    Both the structure and method tested need to be public.