[英]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.rs
和run_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.