rust - 如何将大型 impl 拆分为多个文件?
问题描述
我真的不喜欢类函数的整体实现(用 C++ 说话)。在那种语言中,我可以随意拆分;在 Rust 中,对于哪些文件中的内容有严格的规定。
我有大约 2000 行(没有评论/文档)的impl
结构。从逻辑上讲,它们可以分成不同的集合;用于管理 A 方面的功能,用于管理 B 方面的功能,......它们都在struct
大量使用 's 数据,因此进一步切碎将struct
无济于事。
我在一个答案中看到你可以拥有
// in thing.rs
struct Thing{
.......
}
impl Thing{
fn1
fn2
}
// in more_thing.rs
use crate::thing::*;
impl Thing{
fn3,
fn4
}
// in lib.rs
mod thing;
mod more_thing;
这几乎有效(我很惊讶它完全有效)。它是一种中途之家。问题是对于 more_thing.rs 中的方法,我必须声明Thing
all的字段pub
。这是可行的,但不是很好。还有其他选择吗?
我知道我可以限制pub
范围,但它仍然会破坏封装。
解决方案
模块中的所有非pub
项目在其子模块中仍然可见。只需制作more_thing
一个子模块thing
而不是兄弟姐妹。您可以通过将其放在名为 的目录thing
中并将mod
声明放入其中来做到这一点thing.rs
:
// thing.rs (or thing/mod.rs; see below)
pub struct Thing {
field: i32,
}
// Note the lack of `pub`: `more` is only an implementation detail
mod more;
// thing/more.rs
use super::Thing;
impl Thing {
// Although it is defined in a non-`pub` module, this method will be visible anywhere
// `Thing` is because it is marked `pub` and is a member of `Thing`. You can use
// `pub(crate)` or `pub(super)` instead to get different levels of visibility, or
// leave it private and it will only be available in the current module (thing::more)
pub fn field(&self) -> i32 {
// because more is a submodule of thing, non-`pub` members are visible here.
self.field
}
}
如果您希望将所有与 -Thing
相关的文件保留在thing
目录中,您可以重命名thing.rs
为特殊文件名thing/mod.rs
,它将以完全相同的方式工作。
推荐阅读
- list - 测试 L 是否是一个有效的 Prolog 列表
- events - 如何将事件绑定到 ContentView 的 IsVisible 属性?
- r - 仅在特定列中使用非 NA 创建新列 [R]
- java - 引起:java.lang.IllegalArgumentException: Invalid column * with api >=29
- vba - 如何使用使用输入框从用户那里获取的输入在 VBA 中替换它
- c++ - 为什么我的类变量没有正确初始化?
- r - 合并列并创建另一个列以指定源
- mysql - 在 MySQL 中计算列的简单中位数
- apache-flink - 2 个加入的主题之间的 Flink 流同步
- android - 如何在 Google 地图上获取所有加油站/燃料站/加油站的坐标?