Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include file from another file in the same directory of the same project?

Tags:

rust

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:

  • https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html
  • How do I do a basic import/include of a function from one module to another in Rust 2015?
  • Split a module across several files
  • How to include module from another file from the same project?
  • https://doc.rust-lang.org/stable/rust-by-example/mod.html

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
like image 897
Robin Avatar asked Oct 18 '25 12:10

Robin


1 Answers

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.

like image 73
Raleigh L. Avatar answered Oct 21 '25 01:10

Raleigh L.