Why one module per file?

Sometimes it is tedious to move things around, for example, a file(module M) contains a type T and U, along with their impls, then type T’s impl grows too large, one might want to split this type T into another file, then any user of M has to change it’s import or we re-export T in M.

What do you mean by “split this type T into another file”? You cannot split the type. You CAN split impl freely. impl can be anywhere and it doesn’t affect import or export at all.

1 Like

Here’s an example of what @sanxiyn means:

struct Bar(usize);

impl Bar {
    fn a(&self) {}
}

impl Bar {
    fn b(&self) {}
}

mod sub_bar {
    impl super::Bar {
        pub fn c(&self) {}
    }
}

fn main() {
    let x = Bar(2);
    x.a();
    x.b();
    x.c();
}

[Playground]

1 Like

This is a nice Language Feature.

But now I wonder how can I get cargo to build all those different source files into one Library which could also be used in a different Rust Application?

1 Like

Do you basically mean it is not feasible to change from

src
├── M
│   └── types.rs   // contains type T and U, their impl
└── main.rs         // imports some_module::{T,U}

to (because this creates a new submodule)

src
├── M
│   ├── types.rs    // now contains only U and its impl
│   └── type_T.rs   // contains type T and its impl
└── main.rs         // imports some_module::{T,U}

but to (no adjustment needed)

├── M
│   ├── types.rs    // now contains only T and U
│   ├── impl_T.rs   // contains type T's impl
│   └── impl_U.rs   // contains type U's impl
└── main.rs         // imports some_module::{T,U}

1 Like