rust 在`if cfg!(test)`中未声明的crate或模块,即使在dev-dependencies中已定义

9fkzdhlc  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(147)

下面是错误:

let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
          ^^^^^^^ use of undeclared crate or module `tempdir`

我的货物toml看起来是这样的:

#...
[dev-dependencies]
tempdir = "0.3.7

在代码中:

let path = if cfg!(test) {
            let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
            tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
        } else {
            path
        };

我不明白为什么它失败了,当我运行cargo test时。

46scxncf

46scxncf1#

cfg!宏根据内容计算为常量truefalse,因此在非测试构建中计算为

let path = if false {
    let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
    tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
} else {
    path
};

它仍然有依赖关系,并且会检查所有内容,因此它会看到丢失的crate。相反,你必须从编译中删除整个第一个块:

#[cfg(test)]
let path = {
    let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
    tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
};

相关问题