404*_*und 3 namespaces module rust
使用 C++ 命名空间,我可以将任何文件中的任何内容放在任何位置,并且在编译时它们将“合并”到单个命名空间中。因此,这个文件结构:
\n/* src/main.cpp */\nint main() {\n nsfoo::foo();\n}\n/******/\n\n/* src/foo/function.cpp */\nnamespace foo {\n void foo(nsfoothing thing) {}\n}\n/******/\n\n/* src/foo/structures.cpp */\nnamespace foo {\n struct nsfoothing {};\n\n void nsfooprocessthing(nsfoothing thing) {}\n}\n/******/\nRun Code Online (Sandbox Code Playgroud)\n相当于有一个包含以下内容的文件:
\n/* src/main.cpp */\nnamespace nsfoo {\n struct nsfoothing {};\n void foo(nsfoothing thing) {}\n void nsfooprocessthing(nsfoothing thing) {}\n}\n\nint main() {\n nsfoo::foo();\n}\n/******/\nRun Code Online (Sandbox Code Playgroud)\n或这个文件结构:
\n/* src/main.cpp */\nint main() {\n nsfoo:foo();\n}\n/******/\n\n/* src/foo/foo.cpp */\nnamespace nsfoo {\n struct nsfoothing {};\n void foo(nsfoothing thing);\n void processnsfoothing(nsfoothing thing);\n}\n/******/\nRun Code Online (Sandbox Code Playgroud)\n或这个文件:
\n/* tmp/quickndirtytesting.cpp */\nnamespace foo {\n struct nsfoothing {};\n}\n\nnamespace foo {\n void foo(nsfoothing thing) {}\n void processnsfoothing(nsfoothing thing) {}\n}\n\nint main() {\n nsfoo::foo();\n}\n/******/\nRun Code Online (Sandbox Code Playgroud)\n重点是,对于我如何布局我的“模块”,以及我将什么放入什么文件中,基本上没有任何限制 - 它们在编译时都会“合并”。
\n对于 Rust,我尝试翻译一个应该在 C++ 中工作的东西:
\n/* src/main.rs */\nmod mymod {\n struct Foo {}\n}\n\nmod mymod { // <-- the name `mymod` is defined multiple times. `mymod` must be defined only once in the type namespace of this module.\n struct Bar {}\n}\n\nfn main() {\n // Would reference mymod here, but it produced an error before I even get here.\n}\n/******/\nRun Code Online (Sandbox Code Playgroud)\n并很快发现我使用 C++ 命名空间“将任何内容放置在任何文件结构中的任何位置”的经验在 Rust 中并不完全一样。理想情况下,我希望有一个类似于 C++ 中的结构:
\n.\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.rs\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 mymod\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 agroupoffunctions.rs\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 structures.rs\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 yetanothergroupoffunctions.rs\nRun Code Online (Sandbox Code Playgroud)\n所以我想我的问题是,如何在 Rust 中创建“部分命名空间”,类似于 C++?如果这样的事情不可能,我应该如何组织我的数据结构和功能?
\nkmd*_*eko 11
Rust 没有像 C++ 的命名空间那样的机制。
Rust 的模块是组织代码的方式,但它们不进行任何类型的自动合并。如果您想要更多嵌套文件但以更平坦的路径访问它们,则可以将项目从子模块重新导出到父模块中。
愚蠢的例子:
如果您正在编写代码main.rs并且不想指定plants::trees::Pine,而是想plants::Pine工作。
src/
- main.rs
- plants/
- mod.rs
- trees/
- ...
- ferns/
- ...
- grasses/
- ...
Run Code Online (Sandbox Code Playgroud)
然后您可以将所有内容重新导出plants::trees到plants其mod.rs:
mod trees;
mod ferns;
mod grasses;
pub use trees::*; // <-- re-exports everything
pub use ferns::*;
pub use grasses::*;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |