ProgrammingRust Backend Developer

Explain how the module system and visibility (pub, pub(crate), private) work in Rust. How can a large project be organized to avoid name conflicts?

Pass interviews with Hintsage AI assistant

Answer

The module system in Rust is built around the mod keyword. Modules allow for logical separation of code into files and namespaces. Key points:

  • Everything is private by default within the current module.
  • pub makes an item public to the entire module tree.
  • pub(crate) — accessible throughout the crate (i.e., the library/project).
  • Name conflicts are resolved through namespaces: explicit imports (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;

Trick Question

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

Examples of Real Errors Due to Ignorance of Subtleties


Story

In a project with a complex module structure, a struct was accidentally declared as pub but the module was not exported as pub. Later attempts to use the struct from another crate resulted in an error about type unavailability.

Story

In a large library, different modules exported the same names (for example, types and errors). Blindly using 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.