Pre-RFC: Multiple module blocks


Currently it’s possible to have multiple impl blocks for a given type:

struct Foo;

impl Foo { }
impl Foo { } // totally fine

I just had a thought: why not allow the same for mod { ... } blocks? That is:

mod bar {
    fn baz() { }
mod bar { // causes a compile error in current-day rust
    fn qux() { }

The outcome of this would then be a single bar module that contains 2 fns baz and qux. In current day rust the mod block containing the qux definition causes a compiler error.

The reason I’d like this is because it’s useful when generating code, and it seems like a low-cost, low-risk feature to have. It would also increase consistency w.r.t. how inherent impl blocks for types are handled.

It’s also useful to clearly state that I am only talking about the mod { ... } form. Modules that live in their own files would stay exactly as they are now.

Any ideas on this?


Why this restriction if consistency is important?

Other things to consider:

  • What effect would this have on compile times?
  • What impact would this have on future plans for parameterized modules, e.g. mod foo<T: Debug> { .. }.


I’m not opposed to doing the same for modules in their own files. However, I personally don’t need it, so didn’t think to include that. That’s what feedback like yours is for :slight_smile:

I’m not sure about compile times because I don’t know how rustc handles modules internally. However, I do see a potential for more memory consumption, as needing to find multiple mod blocks/files in order to “compose” a module means the first N-1 mod parts (assuming N parts total) need to be stored somewhere until the last part is found. That said, the option is clearly viable in principle, as something very similar is already happening for impl blocks today, at least conceptually.

I wasn’t aware this was more than a passing thought a couple of Rustaceans had in the vein of “wouldn’t it be nice if …”. To determine the effects, if any, I guess I’d need to read the relevant RFC for parameterized modules. Is there a link to it somewhere?

Perhaps impl blocks can offer some inspiration here as well: they can be parameterized (if the type to which the impl block is associated is also parameterized), and they can also be split up into multiple blocks. I’m just not sure if both are possible at the same time. If so, why not do something similar with modules? And if not, why not copy that behavior to mod blocks?