简体   繁体   English

在 Rust 中使用父目录中的模块

[英]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.rsbin2.rscommon模块。 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.rsbin2.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.

相关问题 如何使用 Cargo/Rust 在模块中包含来自同一目录的文件? - How to include files from same directory in a module using Cargo/Rust? 如何在 Rust 货物项目中使用另一个模块中的一个模块? - How to use one module from another module in a Rust cargo project? 从父目录导入haskell模块 - Importing a haskell module from the parent directory OCaml:顶层目录中父目录的未绑定模块 - OCaml: Unbound module from parent directory in toplevel 来自父目录的python导入模块 - python import module from a parent directory Python - 如何禁用从父目录导入的模块的日志记录? - Python - How to disable logging from a module imported from the parent directory? 从同一父目录中的不同文件夹导入模块时出错 - Error when importing module from a different folder in the same parent directory 从父目录中另一个文件夹中的模块导入 function - Import a function from a module in another folder in parent directory 从当前目录的父目录的另一个子目录导入另一个模块(python) - Importing another module from another subdirectory of the current directory's parent directory (python) 在 Rust 中,是否能够使用来自未导入模块的结构方法是预期的行为? - In Rust, is being able to use a structs methods from an unimported module expected behavior?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM