4

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
4
  • 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) Commented Dec 2, 2019 at 23:30
  • See also How do I import from a sibling module? Commented Dec 2, 2019 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? Commented Dec 3, 2019 at 1: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? and Why can't I import module from different file in same directory? (which was marked as a duplicate of one of the ones you linked, but also has an answer of its own). Commented Dec 3, 2019 at 12:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.