Rust Modules

Written
  • Source: https://doc.rust-lang.org/rust-by-example/mod.html
  • Each file and directory is a module by default.
  • In a directory, mod.rs is the "main" file for the module and the other files are nested modules under that module. Other files must be referenced with mod FILENAME to be included.
  • You can also define nested modules within the same file.
  • Visibility
    • Items in modules are private by default
    • pub makes them visible outside the module.
    • Nested modules within a file can be declared with pub mod to make them public.
    • pub(in path) lets you define specific paths where the item should be importable.
      • e.g. pub(in crate::other_module)
    • pub(self) is public only within the current module, which is effectively the same as the default private visibility.
    • pub(super) makes it visible to the parent module.
    • pub(crate) makes it visible within the whole crate.
    • Notably, access to any item msut be allowed to the importer along the whole chain. Declaring a function pub in a module that isn't visible outside the crate doesn't actually expose that field to external importers. The module itself must be exposed in some way too.
    • In structures, fields and functions are also private by default even if the structure itself is public. All the pub modifiers above apply when you do want to expose them.
  • use syntax
    • You can access anything visible with the entire full path to the item, but use makes it simpler.
    • use crate::a::b::{ fn1, fn2 } will expose fn1 and fn2 in the module's scope.
    • use X as Y will rename the function too.
    • pub use reexports an imported module or other item.
  • super::other_module::X and self::X can help for relative references and to remove ambiguity.

Thanks for reading! If you have any questions or comments, please send me a note on Twitter. And if you enjoyed this, I also have a newsletter where I write about tech thoughts, interesting things I've read, and project updates each Thursday.

You can check out a recent issue, or enter your email below to subscribe.