[英]Use module from parent directory in rust
Is it possible to structure a rust project in this way?是否有可能以这种方式构建 Rust 项目?
Directory structure:目录结构:
src
├── a
│ └── bin1.rs
├── b
│ ├── bin2.rs
└── common
├── mod.rs
from Cargo.toml:来自 Cargo.toml:
[[bin]]
name = "bin1"
path = "src/a/bin1.rs"
[[bin]]
name = "bin2"
path = "src/b/bin2.rs"
I would like to be able to use the common
module in bin1.rs
and bin2.rs
.我希望能够使用
bin1.rs
和bin2.rs
的common
模块。 It's possible by adding the path attribute before the import:可以通过在导入之前添加 path 属性来实现:
#[path="../common/mod.rs"]
mod code;
Is there a way for bin1.rs
and bin2.rs
to use common
without having to hardcode the path?有没有办法让
bin1.rs
和bin2.rs
使用common
而不必对路径进行硬编码?
The recommended method to share code between binaries is to have a src/lib.rs
file.在二进制文件之间共享代码的推荐方法是使用
src/lib.rs
文件。 Both binaries automatically have access to anything accessible through this lib.rs
file as a separate crate.两个二进制文件都可以自动访问可通过此
lib.rs
文件访问的任何内容作为单独的包。
Then you would simply define a mod common;
然后你只需定义一个
mod common;
in the src/lib.rs
file.在
src/lib.rs
文件中。 If your crate is called my_crate
, your binaries would be able to use it with如果您的 crate 名为
my_crate
,则您的二进制文件将能够与
use my_crate::common::Foo;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.