0

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/?

lindhe
  • 806
  • 2
  • 14
  • 32
  • 3
    The `mod` keyword declares a module. Once the module has been declared (eg within `main.rs`) you only need to bring it into scope eg with `use crate::sub_folder` or `use super::sub_folder`. – eggyal Mar 08 '22 at 03:12
  • @eggyal ohhhhhhh I missed the `super` key word. Thanks for the tip – SamNormcoreWayne Mar 08 '22 at 03:22
  • Does this answer your question? [Rust mod files in the same folder vs use](https://stackoverflow.com/questions/67035679/rust-mod-files-in-the-same-folder-vs-use) – Jmb Mar 08 '22 at 07:37
  • @Jmb yes, thx. I fixed it by config my main.rs and lib.rs; – SamNormcoreWayne Mar 09 '22 at 06:10

1 Answers1

5

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.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • 1
    yes I tried to use `use super::sub_folder` or `use crate::sub_folder`. But `cargo check` tells me "unresolved import `super::sub_folder` no `sub_folder` in the rootrustcE0432" – SamNormcoreWayne Mar 08 '22 at 05:51
  • @SamNormcoreWayne If you get that error, "no `sub_folder` in the root", then you must be missing `mod sub_folder;` in `main.rs`. – Kevin Reid Mar 08 '22 at 06:05