3

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
trent
  • 25,033
  • 7
  • 51
  • 90
Robin
  • 423
  • 3
  • 10
  • *In a mainish module (main.rs, lib.rs, or subdir/mod.rs), you need to write `mod a;` for all other modules that you want to use in your whole project (or in the subdir). In any other module, you need to write `use a;` or `use a::foo;`* You need **both** `mod bar;` **and** `use bar;` (actually `crate::bar` here) – trent Dec 02 '19 at 23:30
  • See also [How do I import from a sibling module?](https://stackoverflow.com/questions/30677258/how-do-i-import-from-a-sibling-module) – trent Dec 02 '19 at 23:36
  • Oh, thanks. Why didn't you create a "real" answer so I could have selected it to flag this question as answered? – Robin Dec 03 '19 at 01:19
  • I was on mobile and didn't have the time to dedicate to a good answer. Also, I was pretty sure this had already been answered here, and I prefer to link questions together rather than write new answers. I found [How to include files from same directory in a module using Cargo/Rust?](https://stackoverflow.com/q/46829539/3650362) and [Why can't I import module from different file in same directory?](https://stackoverflow.com/q/55868434/3650362) (which was marked as a duplicate of one of the ones you linked, but also has an answer of its own). – trent Dec 03 '19 at 12:29

1 Answers1

1

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.

Raleigh L.
  • 599
  • 2
  • 13
  • 18