I started a new project in rust (it's my first project in rust, but my first programming language). I added a few functions, types and unit test in main.rs
. Then I wanted to move it in two new files foo.rs
and bar.rs
.
How do I import/include/use bar.rs
from foo.rs
?
I already read:
Neither have the following structure
src/
|-- main.rs
|-- foo.rs
|-- bar.rs
Where foo.rs
is trying to use the content of bar.rs
.
If I try to use a type Bar
declared in bar.rs
directly from foo.rs
, I get:
error[E0433]: failed to resolve: use of undeclared type or module `Bar`
--> src/foo.rs
If I add mod bar
at the beginning of foo.rs
isn't any better:
error[E0583]: file not found for module `bar`
--> src/foo.rs
|
1 | mod bar;
| ^^^
|
= help: name the file either foo/bar.rs or foo/bar/mod.rs inside the directory "src"
And finally (but I wasn't expecting this one to work), with use bar;
in foo.rs
:
error[E0432]: unresolved import `bar`
--> src/foo.rs
|
1 | use bar;
| ^^^ no `grammar` external crate
I answered a very similar question here: https://stackoverflow.com/a/76659218/1576548
There's 2 different problems at hand -- there's how to import code from related modules (e.g. a helpers.rs
) into your main.rs
, but the procedure for doing that is different than importing code from other NON-MAIN modules into other NON-MAIN modules. The example I gave in the aforementioned question uses a.rs
, b.rs
, and main.rs
all in the same directory, where you want to import functions between a.rs
and b.rs
.
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