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.

  • nous@programming.dev
    link
    fedilink
    English
    arrow-up
    10
    ·
    1 year ago

    Best to not think of files as modules. Instead a rust crate is just a tree of modules with the src/main.rs or src/lib.rs being the main entry point.

    Inside these files you define the module structure you want like:

    mod foo {
        mod bar {}
    }
    

    This creates two modules, crate::foo and crate::foo::bar. Now, because you don’t want to have all your code in main.rs/lib.rs rust lets you move the module contents to separate files. But the location of the file needs to match its location in the module structure - from the crates root (not the file it was declared in).

    So when you call mod foo; from src/main.rs it will look for src/foo.rs or src/foo/mod.rs (and you can only have one of these). And the foo::bar - no matter if that is declared in src/main.rs (as above) or inside src/foo.rs or src/foo/mod.rs, it will always look for the bar module contents inside src/foo/bar.rs or src/foo/bar/mod.rs as it is nested inside the foo module - not because the file is next to the current one.

    This means if you had this inside main.rs/lib.rs:

    mod foo {
        mod bar {
            mod baz;
        }
    }
    

    Then it will look for the baz module contents inside src/foo/bar/baz.rs or src/foo/bar/baz/mod.rs - even though those might be the only two files you have.