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/
?
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 yourmod
declarations and your file locations match up to each other.So, if the path is
src/sub_folder/mod.rs
(orsrc/sub_folder.rs
), then you should declare the module inmain.rs
becausemain.rs
(orlib.rs
if you are doing that instead) is the crate root, the place where all top-level modules are declared. That is,main.rs
containsThese two modules are siblings within the crate. Then in order for
sub_mod
to import (not define)sub_folder
, it should contain:or, equivalently (absolute rather than relative path),
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, writemod 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.