如何将大型 impl 拆分为多个文件?

pm1*_*100 10 rust

我真的不喜欢类的函数的整体实现(用 C++ 说)。在那种语言中,我可以随心所欲地拆分事物;在 Rust 中,对于文件中的内容有严格的规则。

impl对于一个结构,我有大约 2000 行(没有评论/文档)。从逻辑上讲,它们可以分解为不同的集合;用于管理方面 A 的功能,用于管理方面 B 的功能,......它们都在struct大数据上浪费时间,因此struct进一步切碎无济于事。

我在一个答案中看到你可以拥有

// in thing.rs

struct Thing{
.......
}

impl Thing{
  fn1
  fn2
}
Run Code Online (Sandbox Code Playgroud)
// in more_thing.rs

use crate::thing::*;
impl Thing{
  fn3,
  fn4
}
Run Code Online (Sandbox Code Playgroud)
// in lib.rs

mod thing;
mod more_thing;
Run Code Online (Sandbox Code Playgroud)

这几乎有效(我很惊讶它完全有效)。它是一种中途的房子。问题是,对于 more_thing.rs 中的方法,我必须声明Thingall的字段pub。这是可行的,但不是很好。还有其他选择吗?

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

tre*_*tcl 12

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;
Run Code Online (Sandbox Code Playgroud)
// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望将所有Thing相关文件保留在thing目录中,您可以重命名thing.rs为特殊文件名thing/mod.rs,它将以完全相同的方式工作。


sny*_*nue -3

Rust 支持多个 impl 块。

in thing.rs

struct Thing {
.......
}

impl Thing {
  fn1
  fn2
}

include!(./thing_2.rs)

Run Code Online (Sandbox Code Playgroud)
// thing_2.rs
impl Thing {
  fn3
  fn4
}
Run Code Online (Sandbox Code Playgroud)

  • 这并没有解决主要问题,即文件太大。OP 提到不希望一个文件中有 2000 行。 (3认同)