将struct移动到单独的文件中而不拆分成单独的模块?

问题描述 投票:7回答:1

我有这个文件层次结构:

main.rs
protocol/
protocol/mod.rs
protocol/struct.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 usemod的各种组合,但不可否认,我正在盲目地捅东西。

是否可以将结构(以及它的impl)拆分为单独的文件而无需创建新的mod?

module rust
1个回答
12
投票

简短的回答:在你的pub use Type中使用mod.rs。完整的例子如下:

我的结构:

src/
├── main.rs
├── protocol
│   └── thing.rs
└── protocol.rs

卖弄.人生

mod protocol;

fn main() {
    let a = protocol::Thing::new();
    println!("Hello, {:?}", a);
}

protocol.人生

pub use self::thing::Thing;
mod thing;

协议/ thing.rs

#[derive(Debug)]
pub struct Thing(i8);

impl Thing {
    pub fn new() -> Thing { Thing(4) }
}

作为管家位,不要将文件调用与语言关键字相同的内容。 struct导致编译问题,所以我重命名了。此外,您的结构创建语法不正确,因此我选择了此示例的较短版本^ _ ^。

并回答标题中提出的问题:文件和模块总是匹配,你不能把东西放在不同的文件中,也不能把它放在不同的模块中。您可以重新导出该类型,但它看起来不像它。

© www.soinside.com 2019 - 2024. All rights reserved.