gpt4 book ai didi

rust - 如何将结构的实现移动到单独的文件中而不将其放入子模块中?

转载 作者:行者123 更新时间:2023-12-02 02:00:21 25 4
gpt4 key购买 nike

我有这个主要功能:

mod tools;

fn main() {
let mut factory = tools::TerminalFactory::new();
let trm: tools::Terminal;

trm = factory.create("TTY1".to_string());
println!("{}", trm);

std::process::exit(0);
}

这是tools/mod.rs:

pub struct Terminal {
id: u32,
pub name: String
}

impl Terminal {
pub fn get_id(self: &Self) -> u32 {
self.id
}
}

impl std::fmt::Display for Terminal {
fn fmt(self: &Self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TERMINAL#{} ({})", self.id, self.name)
}
}

pub struct TerminalFactory {
next_id: u32
}

impl TerminalFactory {
pub fn new() -> TerminalFactory {
TerminalFactory {
next_id: 0
}
}

pub fn create(self: &mut Self, name: String) -> Terminal {
self.next_id += 1;

Terminal {
id: self.next_id,
name: name
}
}
}

如您所见,我在 tools 中有两个结构:tools::TerminalFactorytools::Terminal。我想要做的是在两个单独的文件中实现这两个结构,因为 tools 模块会非常拥挤,我不想用数千行代码把它弄得乱七八糟。

我想不出将这段代码移动到单独的文件并将其保存在 tools 中的方法。当我将它移动到其他文件时,我得到的是,在 tools/mod.rs 中,我必须定义 mod:

mod terminal;
mod terminal_factory;

但这移动结构到tools::terminal_factory::TerminalFactorytools::terminal::Terminal,这不是什么我要。

在没有 *.toml 且没有 cargo 的情况下,这是如何以质朴的方式完成的?

I will certainly use cargo, but I want to understand beforehand how to do this without it.

最佳答案

当您不想公开此模块化结构时,您通常会重新导出更深的类型。

在这里,您的 tools/mod.rs 文件将是

mod terminal;
mod terminal_factory;

pub use {
self::terminal::Terminal,
self::terminal_factory::TerminalFactory,
};

pub use 使外部代码能够使用 TerminalFactory 类型,就好像它是在上层模块中声明的一样。

关于rust - 如何将结构的实现移动到单独的文件中而不将其放入子模块中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69043661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com