I am pretty new to Rust and I find the docs can be a little confusing sometimes so I’d be really thankful for people who can help me understand this.

So for my uni project we are doing part of it in Rust. and I am having issues understanding how the modules function. So here is my example program.

Main.rs does some stuff and then passes a pointer into a function from a separate Rust file. That function then does some more things and passes a new variable into a function form another separate Rust file as a pointer.

main.rs has mod separate_file1; and then in separate_file 1 there is a mod separate_file2;.

The confusion is that separate_file2 does not read from the same directory as main.rs despite being in it. Instead it looks in a sub-folder under the same name.

If someone could explain to me why it works like this and what the best practice is for using modules I would be really thankful. It’s made me struggle a lot.

  • soulsource@discuss.tchncs.de
    link
    fedilink
    arrow-up
    13
    ·
    11 months ago

    If you want your module to contain submodules, it needs to go into a folder. That folder needs to be named like the module.

    It’s explained pretty well in the book, imho: https://doc.rust-lang.org/stable/book/ch07-02-defining-modules-to-control-scope-and-privacy.html

    So, for your example, the file structure could for instance be
    src/main.rs
    src/separate_file1.rs
    src/separate_file1/separate_file2.rs

    An alternative layout that I think is more common would be
    src/main.rs
    src/separate_file1/mod.rs
    src/separate_file1/separate_file2.rs

    Or, if you think separate_file2 could contain submodules at some point, maybe
    src/main.rs
    src/separate_file1/mod.rs
    src/separate_file1/separate_file2/mod.rs