货物抱怨测试模块上未使用 super::* 导入

问题描述 投票:0回答:1

我是 Rust 新手,我正在尝试为我的模块编写一些测试,但货物不断抱怨我的

use super::*;
导入,这对我来说没有意义。看看这个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);
    }
}

如果我运行

cargo check
(或者只是使用 Rust 分析器将文件保存在 VSCode 中),我会收到此警告:

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

但是,如果我删除这个

use
语句,我会收到一个错误(这对我来说绝对有意义):

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

给予:

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;
   |

所以接受Cargo的建议(我有什么资格拒绝它?):

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);
    }
}

我收到和以前一样的警告:

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

除了警告之外,代码编译并且测试成功运行。但这很烦人。我错过了什么吗?或者这可能是一个错误?

rust rust-cargo
1个回答
0
投票

它抱怨是因为导入仅在测试编译时使用,而在正常编译期间不是这种情况,因此据货物所知,导入仍然未使用。如果您使用

tests
属性注释您的
#[cfg(test)]
模块,它将停止抱怨,因为现在导入语句和测试仅一起编译。 即:

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

另请参阅本书了解更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.