Cargo complaining on unused super::* import on tests module

44 Views Asked by At

I'm new to Rust and I'm trying to write some tests to my module, but cargo keeps complaining on my use super::*; import, which doesn't make sense for me. Look at this MCVE:

src/ga/world2.rs:

use crate::ga::individual::*;

#[derive(Debug, Clone)]
pub struct World {
    pub mutation_rate: f64,
    pub crossover_rate: f64,
    pub elitism: usize,
    pub max_generations: usize,
    pub population: Vec<Individual>,
}

impl World {
    pub fn new(
        population_size: usize,
        mutation_rate: f64,
        crossover_rate: f64,
        elitism: usize,
        max_generations: usize,
    ) -> Self {
        World {
            mutation_rate,
            crossover_rate,
            elitism,
            max_generations,
            population: vec![Individual::new(10); population_size],
        }
    }
}

mod tests {
    use super::*;
    #[test]
    fn test_world_new() {
        let world = World::new(4, 0.5, 1., 1, 1000);
        assert_eq!(world.population.len(), 4);
    }
}

If I run cargo check (or just save file in VSCode with Rust Analyzer), I get this warning:

warning: unused import: `super::*`
  --> src\ga\world2.rs:31:9
   |
31 |     use super::*;
   |         ^^^^^^^^

If I, however, drop this use statement, I get an error (which makes absolute sense for me):

mod tests {
    #[test]
    fn test_world_new() {
        let world = World::new(4, 0.5, 1., 1, 1000);
        assert_eq!(world.population.len(), 4);
    }
}

Gives:

error[E0433]: failed to resolve: use of undeclared type `World`
  --> src\ga\world2.rs:33:21
   |
33 |         let world = World::new(4, 0.5, 1., 1, 1000);
   |                     ^^^^^ use of undeclared type `World`
   |
help: consider importing one of these items
   |
31 +     use crate::ga::world2::World;
   |

So accepting the Cargo's suggestion (who am I to decline it?):

mod tests {
    use crate::ga::world2::World;

    #[test]
    fn test_world_new() {
        let world = World::new(4, 0.5, 1., 1, 1000);
        assert_eq!(world.population.len(), 4);
    }
}

I get the same warning as before:

warning: unused import: `crate::ga::world2::World`
  --> src\ga\world2.rs:31:9
   |
31 |     use crate::ga::world2::World;
   |         ^^^^^^^^^^^^^^^^^^^^^^^^

Besides the warning, the code compiles and the tests run succesfully. But this is annoying. Am I missing something? Or maybe this is a bug?

1

There are 1 best solutions below

1
isaactfa On BEST ANSWER

It complains because the import is only used when the tests get compiled which isn't the case during a normal compilation so the import remains unused as far as cargo can tell. If you annotate your tests module with the #[cfg(test)] attribute, it'll stop complaining, because now the import statement and the tests are only compiled together. I.e.:

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

See also The Book for more details.