Hacker News new | ask | show | jobs
by chrismorgan 2046 days ago
One important technical reason is that you need to be able to add attributes to modules, like these examples:

  // Only compile this code if the “foo” Cargo feature is enabled.
  #[cfg(feature = "foo")]
  pub mod foo;

  // Platform-specific stuff, as with std::os.
  pub mod os {
      #[cfg(windows)]
      pub mod windows;

      #[cfg(unix)]
      pub mod unix;
  }

  // You can even choose which file to load the module from.
  #[cfg_attr(windows, path = "windows/mod.rs")]
  #[cfg_attr(unix, path = "unix/mod.rs")]
  #[cfg_attr(not(any(windows, unix)), path = "null/mod.rs")]
  mod platform_impl;
So they need to at least be addressable.
1 comments

Interesting. This made me realize that a possible reason why some find the modules concept confusing is that it conflates the concepts of inclusion and namespacing.

edit: corrected typo

Has the joke flown over my head, or have you conflated the words "conflate" (confuse) and "conflagrate" (burn)?

Edit: I honestly think I might have just misunderstood some play on words you're trying to make. It would be something around setting namespaces and inclusion on fire, but none of the combinations I've tried in my head work out quite right.

D'oh! Thanks for the correction; there was no pun - I just intended that it combined the two concepts :-)
It confused me for a long time because:

- Other languages like C++ and C# emphasize how much namespaces are _not_ connected to files at all

- I just ignored it and wrote everything in one big file, because the Rust compiler is just as slow either way. Even in C++ it's arguable whether splitting a file will result in faster or slower compiles, because of the outrageous behavior of #include

But once I realized every file is a module, it slowly started to make sense.

Rust modules are primarily about namespacing, which is why the book only mentions the inclusion behavior in one short section at the end of the relevant chapter. For a non-namespacing include, there’s the `include!` macro.
The `include!` is not intended to be used as a _generic_ inclusion mechanism¹:

> Using this macro is often a bad idea, because if the file is parsed as an expression, it is going to be placed in the surrounding code unhygienically. This could result in variables or functions being different from what the file expected if there are variables or functions that have the same name in the current file.

¹=https://doc.rust-lang.org/std/macro.include.html

I fail to see how you draw your conclusion from that statement. It warns about the macro’s potentially surprising behavior, but doesn’t speak to the designers’ intent at all.

`include!` is analogous to C’s `#include`: it textually pastes the file’s contentents in place of the macro, but I can’t think of another way that a textual (vs. semantic) include mechanism would work.