11

After reading this, I'm wondering why there is a mod keyword and mod.rs?

I assumed that the directory hierarchy can describe the module as well.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
bitnick
  • 1,903
  • 3
  • 16
  • 22

2 Answers2

17

There are a couple of reasons why modules must be explicitly declared:

  • Modules can be public (pub mod foo;) or private (mod foo;).

  • They can have attributes applied to them, attributes that couldn’t sit inside the file; there are two primary examples of that: #[path = "x.rs"] specifying a different path, and #[cfg(…)], for conditional compilation, for cases where the module would fail to parse or have its macros expand.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • 2
    I'd also like to add that Rust doesn't compile files just because they exist; there must be a module definition somewhere in the crate pulling it in. – llogiq Sep 28 '15 at 10:06
  • 3
    @llogiq: the question is about that very point: why is it *not* done that way? – Chris Morgan Sep 28 '15 at 10:18
  • Ok, I may need to rephrase that: It makes sense not to blindly compile arbitrary `.rs` files, just because they're lying around. Why compile something you don't use? – llogiq Sep 28 '15 at 10:32
  • 2
    @llogic: I disagree. There is practically always a direct correspondence between the .rs files in the tree and the modules; were it not for the conditional compilation attributes matter, there really would be no reason for `mod` items—it *could* be handled automatically. And frankly, I often feel it might have been better if we had done thus, though it would require slightly more careful handling of module attributes before parsing the rest of a file and might have *slightly* muddied the phases of the compiler. But there really is no fundamental reason why we couldn’t do without `mod` items. – Chris Morgan Sep 28 '15 at 12:06
  • @llogiq why have a `.rs` file lying around that shouldn't be compiled? – scubbo Apr 12 '23 at 02:54
  • You could conditionally compile a module e.g. `#[cfg(feature = "foo")]` mod foo; which would only use `foo.rs` if the feature is active. – llogiq May 04 '23 at 09:46
8

While it can, it can also be overridden:

#[path = "somewhere/else"]
mod lol;
Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99