Nilanjan Goswami
Nilanjan Goswami

Reputation: 41

How to access modules from parent or sibling folder modules?

I am trying to access modules from the parser.rs and another.rs in the solve.rs. How to include those modules and use the "use statements"? If that is not possible what should be the code structure?

Here is the application folder tree:

app/src
--- main.rs
--- another.rs
--- mod.rs
--- parser/
-------- parser.rs
-------- mod.rs
--- solver/
-------- solve.rs
-------- mod.rs

Upvotes: 4

Views: 2510

Answers (2)

link
link

Reputation: 2419

To access parser/parser.rs and another.rs from anywhere in your crate, you can use absolute paths (here I am also using nested paths, which is not required but makes the structure of modules more clear):

use crate::{
    parser::parser,
    another,
};

You can also use relative paths with super, which refers to the parent module. More information is avaiable in @Ishmaeel's answer.


Regarding your code structure, it seems a little strange why you have mod.rs (not wrong, but just strange, especially 0; you can totally leave 1 and 2 if you like it, but 0 might confuse you):

app/src
    main.rs
    another.rs
    mod.rs        // 0
    parser/
        parser.rs
        mod.rs    // 1
    solver/
        solve.rs
        mod.rs    // 2
  • Regarding 1 and 2:

    mod.rs was used in the 2015 edition for being able to create nested modules, but is no longer needed in the 2018 edition (assuming that you are using the currently newest and default for cargo 2018 edition, see What are editions?):

    A foo.rs and foo/ subdirectory may coexist; mod.rs is no longer needed when placing submodules in a subdirectory.

  • Regarding 0:

    The module you are defining via this is actually named mod (not src as you may have expected, though I'm not sure at all what you expected here), I'm unsure if you meant to do that. However if you did, there is still a way to access it via r# - raw identifiers, available since Rust 1.30:

    use crate::r#mod;
    

    If you don't want to write r#mod all over the place, you can use as like this:

    use crate::r#mod as new_name;
    

    Then you can refer to the module via new_name.

Upvotes: 1

Ishmaeel
Ishmaeel

Reputation: 14373

Your first option is absolute paths:

use crate::parser::Whatever;
use crate::solver::Another;

crate here is a keyword representing the crate root.

You can also use relative paths for advanced scenarios. Both solutions are discussed very nicely in the relevant Rust Documentation

Also, don't forget that you need to make the modules public. They will be private by default and not accessible from parents or siblings.

Upvotes: 3

Related Questions