This is my file structure:
src/
├── main.rs
├── args_parser.rs
└── trim.rs
In args_parser.rs
I have enum Args
that I want to use in main.rs
and in trim.rs
, but when trying to run trim.rs
with mod args_parser;
at the beginning it spits out this error message:
error[E0583]: file not found for module `args_parser`
--> src/trim.rs:1:5
|
1 | mod args_parser;
| ^^^^^^^^^^^
|
= help: name the file either trim/args_parser.rs or trim/args_parser/mod.rs inside the directory "src"
It seems like it expects trim.rs to import only files that are from this module, but in Rust by example (https://doc.rust-lang.org/rust-by-example/mod/split.html) it says "This declaration will look for a file named my.rs
or my/mod.rs
".
Is there any way I can import this file from main.rs
and from trim.rs
?
You seem to be mixing up declaring a module (mod <name>
) and importing a module (use <name>
). The mod
keyword is used to declare a new module, either in another file, or with curly braces immediately following the keyword. You can then import the module with use
.
When using mod
to declare a module in another file, it looks in specific locations. For example, when you use the following statement in main.rs
, mod.rs
, or lib.rs
...
mod abc;
...the compiler will search for contents of the module in ./abc.rs
and abc/mod.rs
. However, if I have the same statement in a different file, like def.rs
, it will instead check in def/abc.rs
and def/abc/mod.rs
. This is why your code isn't compiling.
To fix this, declare the module in your main file, and then import it elsewhere. This is what the code would look like:
// in main.rs
mod args_parser;
mod trim;
use args_parser::...; // use whatever you need in main
// in trim.rs
use crate::args_parser::...; // use whatever you need in trim - note the crate:: prefix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With