Hacker News new | ask | show | jobs
by pornel 2046 days ago
Files aren't modules. Modules are defined in the source code the same way as any named "item" in the language, like structs and functions.

The only difference is that content of `{}` following the definition of a module can be read from another file.

You can have a module without a file:

    mod foo {
       fn function_in_foo() {}
       mod bar {
          // this is crate::foo::bar module!
       }
    }

but if you omit {}:

    mod foo;

Rust will look for `foo.rs` to drop its content where the {} should have been. But namespacing is governed by `mod` declarations alone, not files.
1 comments

That's not how I understand it.

Every file is a module, but not every module is a file.

If `mod foo;` is the only way to make sure a file's code gets compiled, then at some point every file gets its own module, right?

> If `mod foo;` is the only way to make sure a file's code gets compiled, then at some point every file gets its own module, right?

There’s also the `include!` macro which can read a source file without making it a module and the `#[path=...]` directive which can let you use the same source file for several modules.

If you want to, you can easily make a project comprised of many modules and using only one file (or zero files)

Creating a single module from many files is also possible. It can be done with clumsy C-style includes, or more idiomatically composed from `pub use` of items from private modules. `impl` blocks can be anywhere.

The point is, files and modules are decoupled. Files just happen to be a convenient default for modules, but they aren't semantically special in Rust. There's no syntax or privacy boundary specific to files.

) Cargo.toml with `[lib] path = "/dev/stdin"` + `echo 'fn main() {}' | cargo build` happens to work :)