The module system in Rust is built around the mod keyword. Modules allow for logical separation of code into files and namespaces. Key points:
pub makes an item public to the entire module tree.pub(crate) — accessible throughout the crate (i.e., the library/project).use mod_name::item) and aliases.For large projects, it is recommended to use a module tree with public interfaces described only through lib.rs or main.rs while keeping the rest private:
mod network; mod storage; pub use network::api;
If a struct is declared as pub, will it be accessible to other crates?
Answer: No, simply marking a struct as pub is not enough. It must also be declared in a module that is accessible to the external crate (pub mod), and the struct’s fields must be public for direct access.
Example:
mod foo { pub struct Bar; } // Bar is not visible outside the crate because foo is private
Story
Story
use * led to name conflicts during compilation. The solution was to add aliases and import only the needed items.Story
Many newcomers create a pub struct but leave the fields private, making it impossible to initialize them outside the module. As a result, a function from another module couldn't create the struct directly, causing errors until the fields or constructors were made public.