Module 是否将struct移动到单独的文件中而不拆分为单独的模块?
我有以下文件层次结构:Module 是否将struct移动到单独的文件中而不拆分为单独的模块?,module,rust,Module,Rust,我有以下文件层次结构: main.rs 协议/ 协议/模块rs 协议/结构 在struct.rs中: pub struct Struct { members: i8 } impl Struct { pub fn new() -> Struct { Struct { 4 } } } 我如何访问它,因为: mod protocol; protocol::Struct::new(); // As opposed to: // protocol::st
main.rs
协议/
协议/模块rs
协议/结构
在struct.rs
中:
pub struct Struct {
members: i8
}
impl Struct {
pub fn new() -> Struct {
Struct { 4 }
}
}
我如何访问它,因为:
mod protocol;
protocol::Struct::new();
// As opposed to:
// protocol::struct::Struct::new();
我尝试过各种各样的组合,包括pub
use
和mod
,但不可否认,我是在盲目地戳东西
是否可以将一个结构(及其
impl
)拆分为一个单独的文件,而不必创建一个新的mod?简单回答:在mod.rs中使用pub use Type
。一个完整的例子如下:
我的结构:
src/
├── 梅因
├── 协议
│ └── 东西
└── 礼宾
main.rs
mod protocol;
fn main() {
let a = protocol::Thing::new();
println!("Hello, {:?}", a);
}
pub use self::thing::Thing;
mod thing;
#[derive(Debug)]
pub struct Thing(i8);
impl Thing {
pub fn new() -> Thing { Thing(4) }
}
协议.rs
mod protocol;
fn main() {
let a = protocol::Thing::new();
println!("Hello, {:?}", a);
}
pub use self::thing::Thing;
mod thing;
#[derive(Debug)]
pub struct Thing(i8);
impl Thing {
pub fn new() -> Thing { Thing(4) }
}
协议/事物.rs
mod protocol;
fn main() {
let a = protocol::Thing::new();
println!("Hello, {:?}", a);
}
pub use self::thing::Thing;
mod thing;
#[derive(Debug)]
pub struct Thing(i8);
impl Thing {
pub fn new() -> Thing { Thing(4) }
}
作为内务管理的一部分,不要像调用语言关键字一样调用文件<代码>结构
导致编译问题,因此我将其重命名。此外,您的结构创建语法不正确,因此我为本例选择了较短的版本^ ^
为了回答您在标题中提出的问题:如果不使用深奥的功能,文件总是会创建一个新的模块-如果不将某个文件放入另一个模块,您就不能将其放入另一个文件中。您可以重新导出该类型,使其看起来不像它
进一步说明:mod
关键字告诉编译器按该名称查找文件,并将其作为模块从当前文件中引用。例如,mod协议
将查找文件protocol.rs
,其行为与包含其内容的文件类似,类似于:
mod protocol {
// ... contents here
};
有关更多详细信息,请参阅。哈哈,我一直在为自己编译而苦苦挣扎。我不知道我通常会深入到一个模块的层次。我觉得在我见过的锈迹中,更宽、更平坦的锈迹更为常见。吹毛求疵:这里有
include代码>宏,可用于将单个模块拆分为多个文件。这可以说是对它的滥用,因为AFAIU添加它是为了满足代码生成的需要scenarios@RenatoZannon:include
是应该以巨大的成本避免的事情;它有一些相当奇怪的怪癖,并且不容易正确使用。