Rust Programming: Alternate File Paths

0

Rust supports an older style of file path for modules, in which the module code is stored in a file named mod.rs. This style is still supported, but it is no longer considered idiomatic.

For a module named front_of_house declared in the crate root, the compiler will look for the module's code in the following locations:

  • src/front_of_house.rs (idiomatic)
  • src/front_of_house/mod.rs (older style)

For a module named hosting that is a submodule of front_of_house, the compiler will look for the module's code in the following locations:

  • src/front_of_house/hosting.rs (idiomatic)
  • src/front_of_house/hosting/mod.rs (older style)

Example

Consider the following Rust project:

src/
├── front_of_house.rs
│   └── mod.rs
└── hosting.rs

The front_of_house module has two files: front_of_house.rs and mod.rs. The hosting module is a submodule of front_of_house and is defined in the file hosting.rs.

Which style should I use?

It is generally recommended to use the idiomatic style of file paths for modules. This style is more concise and easier to read. It also avoids the potential confusion of having multiple files named mod.rs open in your editor at the same time.

However, there are some cases where you may want to use the older style of file paths. For example, if you have an existing Rust project that uses the older style, you may not want to migrate it to the idiomatic style. Or, you may be working on a project with other developers who prefer the older style.

Ultimately, the decision of which style to use is up to you. But it is important to be consistent with the style that you choose. Using a mix of both styles for different modules in the same project can be confusing for people navigating your project.

Additional notes

  • If you use both styles for the same module, you'll get a compiler error.
  • The main downside to the style that uses files named mod.rs is that your project can end up with many files named mod.rs, which can get confusing when you have them open in your editor at the same time.
  • The idiomatic style of file paths is also supported by Cargo, the Rust package manager. This means that you can use Cargo to build and test your project without any special configuration.

Post a Comment

0Comments
Post a Comment (0)