Rust: Cannot access functions in subdirectories

Viewed 265

I am learning rust and am going through the book and have run into a question. Is it possible to access files within a folder? I am currently having issues with this.

Here is a project which demonstrates the issue: https://github.com/joemspalding/rust-stack-overflow-file-example/tree/master/src

In this project, I can successfully import functions from a different file, however, trying to access a file from a different folder is where I lose understanding syntactically. I feel I've tried nearly every combination of

mod foo;
mod foo::bar;
use foo;
use foo::bar;

Currently, running cargo run produces the following compile time error

   Compiling my-project v0.1.0 (J:\Projects\rust\the_book\ch7\my-project)
error[E0432]: unresolved import `foo`                                                      
 --> src\main.rs:1:5
  |
1 | use foo::bar;
  |     ^^^ use of undeclared type or module `foo`

error: aborting due to previous error                                                      

For more information about this error, try `rustc --explain E0432`.
error: could not compile `my-project`.

To learn more, run the command again with --verbose.

I've been reading into this for hours and all of the resources I can find have great examples of reading code from a file on the same level, but not on reading code through folders.

Another common line I've seen is with the use of folder/mod.rs This seems unstylistic of rust after an update in 2018 and I'd like to avoid it if possible.

1 Answers

You must use mod.rs. It is the preferred option in rust 2018 and above. Module definitions aren't file paths and shouldn't be treated as such. Think of them more as C++ namespaces.

You could also choose to rename your mod.rs to match the name of the folder it is in (Ex: example_a/mod.rs -> example_a/example_a.rs). However I almost never this done and I find its much easier to navigate code with mod.rs.

If your mod.rs doesn't have any useful code, maybe you don't need a submodule.

A mod.rs should have code which relates to its sub modules. If it is only a couple lines long, you may want to skip adding the folder entirely since it doesn't sound like it has any purpose in your specific use case. This isn't like the empty __init__.py files of python 2.

Related