Search code examples
rustrust-cargorust-analyzer

RUST: Is there a more elegent way to import mod?


Here is my project structure:

.
└── src
    ├── main.rs
    ├── sub_folder
    │   └── mod.rs
    └── sub_mod.rs

in sub_mod.rs, cargo won't warn me if I import sub_folder/ like:

#[path = "./sub_folder/mod.rs"]
mod sub_folder;

but I cannot do

mod sub_folder

but in main.rs it works!!

Is there a gentler way in sub_mod.rs to import sub_folder/?


Solution

  • You should almost never use the #[path] attribute. It is for putting source code in nonstandard locations, and it is very easy to make a mistake using it. Instead, make sure your mod declarations and your file locations match up to each other.

    So, if the path is src/sub_folder/mod.rs (or src/sub_folder.rs), then you should declare the module in main.rs because main.rs (or lib.rs if you are doing that instead) is the crate root, the place where all top-level modules are declared. That is, main.rs contains

    mod sub_folder;
    mod sub_mod;
    

    These two modules are siblings within the crate. Then in order for sub_mod to import (not define) sub_folder, it should contain:

    use super::sub_folder;
    

    or, equivalently (absolute rather than relative path),

    use crate::sub_folder;
    

    A tip: If you are using an editor compatible with rust-analyzer, you can have it help you with creating modules properly. Don't create a file; instead, write mod my_module; somewhere in your existing sources, wait for the "missing file" error to appear, then run the offered fix “Create module”. rust-analyzer will create the file in the correct location for you.