'How to break a large Rust impl block into files?

Here is what I have in foo.rs:

pub struct Foo {
  // a few attributes
}

impl Foo {
  // 20+ public functions 
}
// 100+ tests

The file is too long (2000+ lines of code). How can I break it into files without changing the structure of the code: I want to still have one struct Foo with many functions and many unit tests.



Solution 1:[1]

Rust allows you to have impl blocks in separate files. So you can have, for example:

In file1.rs:

pub struct Foo {
    // a few attributes
}

In file2.rs:

impl Foo {
    // some methods
}    

In file3.rs:

impl Abc for Foo {
    // other methods
}

In file4.rs:

impl Xyz for Foo {
    // other methods
}

It's also worth mentioning that if you have private fields in your struct Foo (the default, i.e. you don't add pub or any other visibility modifiers to your fields) , you can still access them in other files, but there is a restriction: they can only be accessed by the current module and its descendants.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1