首页 > 解决方案 > 如何将大型 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 中的方法,我必须声明Thingall的字段pub。这是可行的,但不是很好。还有其他选择吗?

我知道我可以限制pub范围,但它仍然会破坏封装。

标签: rust

解决方案


模块中的所有非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,它将以完全相同的方式工作。


推荐阅读