简体   繁体   English

从 rust 中的不同模块访问 function

[英]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. module1test不是maintest :每个板条箱只有在测试它本身时才会打开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.

相关问题 Rust,相同类型,来自同一模块的不同导入的不同路径 - Rust, same type, different paths from separate imports of the same module 如何从Rust中的模块导入单个功能? - How can I import a single function from a module in Rust? 从 Rust 中的 function 返回值的不同方法是什么? - What are the different ways to return a value from a function in Rust? ACCESS_VIOLATION 从 Rust 调用 Btrieve BTRCALL 函数 - ACCESS_VIOLATION calling Btrieve BTRCALL function from Rust Rust:从 function 返回一个通用结构,其中(仅)<t> 是不同的</t> - Rust: return a generic struct from a function where (only) <T> is different 在 Rust 中的同一 crate 文件中从另一个模块调用一个模块的 function - Call function of one module from another module within same crate file in Rust 是否可以在Rust中的不同源文件中包含一个模块 - Is it possible to have a module in different source files in Rust 我如何打电话给Z72812E30873455DCEE2D1E2D1EE26E4ABZ ZC1C425268E6838385D1AB5074C174C174C174C174F14Z in Z72812E3087345555DCEE2CE2CE2D1EE2D1EE2D1EE26E26E4ABZ INLINE ASM MODLINE ASM MODLINE ASM MODLINE ASM MODLINE - How can I call a rust function in rust inline asm module Rust 中的跨模块函数调用 - Cross-module function call in Rust 如果 rust 模块 function 是私有的怎么办 - What to do if rust module function is private
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM