使用C++命名空间,我可以将任何文件中的任何内容放在任何位置,并且在编译时它们将"合并"到单个命名空间中.因此,此文件 struct :

/* src/main.cpp */
int main() {
    nsfoo::foo();
}
/******/

/* src/foo/function.cpp */
namespace foo {
    void foo(nsfoothing thing) {}
}
/******/

/* src/foo/structures.cpp */
namespace foo {
    struct nsfoothing {};

    void nsfooprocessthing(nsfoothing thing) {}
}
/******/

相当于拥有一个包含以下内容的文件:

/* src/main.cpp */
namespace nsfoo {
    struct nsfoothing {};
    void foo(nsfoothing thing) {}
    void nsfooprocessthing(nsfoothing thing) {}
}

int main() {
    nsfoo::foo();
}
/******/

或者这个文件 struct :

/* src/main.cpp */
int main() {
    nsfoo:foo();
}
/******/

/* src/foo/foo.cpp */
namespace nsfoo {
    struct nsfoothing {};
    void foo(nsfoothing thing);
    void processnsfoothing(nsfoothing thing);
}
/******/

或此文件:

/* tmp/quickndirtytesting.cpp */
namespace foo {
    struct nsfoothing {};
}

namespace foo {
    void foo(nsfoothing thing) {}
    void processnsfoothing(nsfoothing thing) {}
}

int main() {
    nsfoo::foo();
}
/******/

需要指出的是,对于我如何布局我的"模块",以及我放在哪个文件中的内容,基本上没有任何限制--它们在编译时都会"合并".

对于Rust,我try 翻译一种应该在C++中工作的东西:

/* src/main.rs */
mod mymod {
    struct Foo {}
}

mod mymod { // <-- the name `mymod` is defined multiple times. `mymod` must be defined only once in the type namespace of this module.
    struct Bar {}
}

fn main() {
    // Would reference mymod here, but it produced an error before I even get here.
}
/******/

并很快发现,我在C++命名空间中"将任何东西放在任何文件 struct 中的任何位置"的体验在Rust中的工作原理并不完全相同.理想情况下,我希望有一个类似于C++的 struct :

.
└── src
    ├── main.rs
    └── mymod
        ├── agroupoffunctions.rs
        ├── structures.rs
        └── yetanothergroupoffunctions.rs

所以我想我的问题是,如何在Rust中创建类似于C++的"部分名称空间"?如果这样的事情是不可能的,我应该如何组织我的数据 struct 和功能?

推荐答案

Ruust没有像C++的S命名空间那样的机制.

Rust的模块是组织代码的方式,但它们不执行任何类型的自动合并.如果您想要更多的嵌套文件,但又想以更平坦的路径访问它们,那么您可以从子模块将项重新导出到父模块中.


愚蠢的例子:

如果您正在用main.rs编写代码,并且不想指定plants::trees::Pine,而是希望plants::Pine起作用.

src/
- main.rs
- plants/
  - mod.rs
  - trees/
    - ...
  - ferns/
    - ...
  - grasses/
    - ...

然后,您可以在ITS mod.rs中将从plants::treesplants的所有内容重新导出:

mod trees;
mod ferns;
mod grasses;

pub use trees::*; // <-- re-exports everything
pub use ferns::*;
pub use grasses::*;

Rust相关问答推荐

在HashMap中插入Vacant条目的可变借位问题

如何在tauri—leptos应用程序中监听后端值的变化?""

把Vector3变成Vector4的绝妙方法

使用pyo3::Types::PyIterator的无限内存使用量

在自定义序列化程序中复制serde(With)的行为

如何高效地将 struct 向量中的字段收集到单独的数组中

不能在一个代码分支中具有不变的自身borrow ,而在另一个代码分支中具有可变的self borrow

为什么HashMap::get和HashMap::entry使用不同类型的密钥?

`actix-web` 使用提供的 `tokio` 运行时有何用途?

为什么实现特征的对象期望比具体对象有更长的生命周期?

当推送到 HashMap 中的 Vector 时,类型 `()` 无法取消引用

中文优化标题:跳出特定循环并返回一个值

go 重并堆积MPSC通道消息

没有得到无法返回引用局部变量`queues`的值返回引用当前函数拥有的数据的值的重复逻辑

如何限制通用 const 参数中允许的值?

`map` 调用在这里有什么用吗?

我如何将特征作为 struct 的拥有字段?

如何为枚举中的单个或多个值返回迭代器

Rust 中的运行时插件

Rust:为什么在 struct 中borrow 引用会borrow 整个 struct?