I am confused about modules/files

Could someone please explain what is the use of mod name; and use crate::name in the context of main.rs versus in the context of a regular file?
I am really confused about why I have to do mod xyz; before I can do use xyz::*;, but that only works in main.rs.

Basically mod abc is a declaration to rust that there exists a file with the name abc.rs (+ some details regarding folders), and that you'd like to load it in as a module. If you never list a file in a mod statement everywhere, then it wont be compiled.

Now just because you created a module doesn't mean you can access everything in it by default. If something inside the module is private, you can't access it at all, and if it's public, you have to ask for it.

3 Likes

mod works the same as fn, struct, and enum — it creates a new item with a name, right there where you write the definition.

Then when you want to use a function/struct/enum/module somewhere else by referring to it by its short name, you get an alias with use.

Slight clarification that mod can be declared without requiring a separate file. See: Bringing Paths Into Scope with the use Keyword - The Rust Programming Language

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.