[英]Access function from a different module in rust
If I have the following:如果我有以下情况:
├── Cargo.lock
├── Cargo.toml
├── main
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── module2
│ ├── Cargo.toml
│ └── src
│ ├── lib.rs
│ └── builder.rs
Where the Cargo.toml
file in the root is the following:根目录中的
Cargo.toml
文件如下:
[workspace]
members = [
"main",
]
I want to access a function from builder.rs
in main when testing(ie cfg(test)
), how can I do so?我想在测试时从 main 中的
builder.rs
访问 function(即cfg(test)
),我该怎么做?
Module2 is a library(it was created by running cargo new module2 --lib
. Module2 是一个库(它是通过运行
cargo new module2 --lib
创建的。
I tried the following:我尝试了以下方法:
// 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;
/*
...
*/
This doesn't work and I get the following error:这不起作用,我收到以下错误:
error[E0432]: unresolved import `module2::build`
--> main/src/main.rs:3:5
|
3 | use module2::build;
| ^^^^^^^^^^^^^^ no `build` in the root
test
of module1
is not test
of main
: each crate gets cfg(test)
turned on only when it itself is being tested, not when a dependency of it is being tested. module1
的test
不是main
的test
:每个板条箱只有在测试它本身时才会打开cfg(test)
,而不是在测试它的依赖项时。
You can use cfg(debug_assertions)
as an approximation or a custom feature.您可以使用
cfg(debug_assertions)
作为近似值或自定义功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.