使用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 和功能?