从锈蚀中的不同模块访问功能

  • 本文关键字:模块 访问 功能 rust
  • 更新时间 :
  • 英文 :


如果我有以下内容:

├── Cargo.lock
├── Cargo.toml
├── main
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── module2
│   ├── Cargo.toml
│   └── src
│       ├── lib.rs
│       └── builder.rs

其中根目录中的Cargo.toml文件如下:

[workspace]
members = [
"main",
]

我想在测试时访问builder.rs中的一个函数(即cfg(test)(,我该怎么做?

Module2是一个库(它是通过运行cargo new module2 --lib.创建的

我尝试了以下方法:

// module2/builder.rs
pub fn build() { /*...*/ }
// module2/lib.rs
#[cfg(test)]
mod mock;
#[cfg(test)]
pub use mock::build;
// main/Cargo.toml
// ...
[dependencies]
module2 = { path = "../module2" }
// main.rs
#[cfg(test)]
use module2::build;
/*
...
*/

这不起作用,我得到以下错误:

error[E0432]: unresolved import `module2::build`
--> main/src/main.rs:3:5
|
3 | use module2::build;
|     ^^^^^^^^^^^^^^ no `build` in the root

module1test不是maintest:每个机箱只有在测试其自身时才打开cfg(test),而不是在测试其依赖项时打开。

可以将cfg(debug_assertions)用作近似值或自定义特征。

最新更新