简体   繁体   English

在标准库 Rust package 结构中放置“通用命令行”工具的位置?

[英]Where to place "common command line" tools in a standard library Rust package structure?

I'm developing a library.我正在开发一个图书馆。 For internal development experiments I need a bunch of binary command line entry points that I can execute.对于内部开发实验,我需要一堆可以执行的二进制命令行入口点。 I'm using a standard project layout like described in this answer under "Flexible".我正在使用标准项目布局,如“灵活”下的此答案中所述。

What I'd like to achieve: Certain functionality in my command line tools is similar, and I'd like to move that out into its own module.我想实现的目标:我的命令行工具中的某些功能是相似的,我想将它移到它自己的模块中。 Ideally I'd like to introduce a cli_common.rs module containing some helper functions here in the package structure:理想情况下,我想在 package 结构中引入一个包含一些辅助函数的cli_common.rs模块:

.
├── Cargo.toml
└── src
    ├── bin
    │   ├── cli_common.rs
    │   ├── run_foo.rs (uses cli_common)
    │   └── run_bar.rs (uses cli_common)
    ├── lib.rs
    └── <various-lib-related-sub-modules>

This doesn't seem to be possible, because the compiler expects every module under bin to have a main function.这似乎是不可能的,因为编译器希望bin下的每个模块都有一个main function。

This suggest that I have to move the functionality of cli_common.rs into the library itself.这表明我必须将cli_common.rs的功能移到库本身中。 This doesn't feel great, because it mixes "peripheral" logic with "core" logic, and I'd like to avoid having this functionality as part of the public interface of the library.这感觉不太好,因为它将“外围”逻辑与“核心”逻辑混合在一起,我想避免将此功能作为库公共接口的一部分。

Is there a trick to have such a cli_commons.rs without having to move it into the library?有这样一个cli_commons.rs而不必将其移动到库中的技巧吗?

I found a solution based on this answer .我找到了一个基于这个答案的解决方案。

For simple cases, an extra crate can be avoided by moving the cli_common.rs somewhere, where the compiler doesn't expect a main .对于简单的情况,可以通过将cli_common.rs移动到编译器不期望main的地方来避免额外的 crate。 In my example I modified the structure for instance to:在我的示例中,我将结构修改为:

.
├── Cargo.toml
└── src
    ├── bin
    │   ├── cli_common.rs
    │   │   └── cli_common.rs
    │   ├── run_foo.rs
    │   └── run_bar.rs
    ├── lib.rs
    └── <various-lib-related-sub-modules>

Within run_foo.rs and run_bar.rs , I can now use mod combined with a #[path] attribute :run_foo.rsrun_bar.rs中,我现在可以将mod#[path]属性结合使用:

#[path="cli_common/cli_common.rs"]
mod cli_common;

For more complex scenarios, going for a separate crate may be preferred.对于更复杂的场景,可能首选单独的箱子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM