Skip to content

Instantly share code, notes, and snippets.

@sam0x17
Last active October 12, 2023 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam0x17/46687df71af4979accf44a2c3416610a to your computer and use it in GitHub Desktop.
Save sam0x17/46687df71af4979accf44a2c3416610a to your computer and use it in GitHub Desktop.
Cheat sheet / beginner guide for how modules work in Rust
mod some_mod;

Simply means "there exists some file called some_mod.rs in this directory, or there exists some directory called some_mod in this directory that contains a file called mod.rs. Typing this line will make whatever content contained within the file (some_mod/mod.rs or some_mod.rs) available in this file via some_mod::whatever.

So Rust source files are modules. There is also a handy inline syntax for defining a short sub-module in the current file/module without needing to have a separate file for this module. This syntax is the source of confusion for a lot of people as it makes them think they have to write mod some_mod { to define any modules. Nope, this is just an inline shortcut for making a separate file and putting stuff in there, like the following:

mod some_other_mod {
    // stuff in here
}

The above simply creates a module called some_other_mod within the current module with the specified contents. This again is just a shortcut for making a file in the same directory called some_other_mod.rs with the contents // stuff in here and declaring it by writing mod some_other_mod. You can also nest these.

Other than your crate's root lib.rs or main.rs file, every rust source file must have exactly one module declaration (a mod some_module; statement) somewhere in the source code that lets cargo know that this file exists. If you simply want to bring a module into scope, you can do a use statement, like the following:

use some_mod;

Another caveat is when you are already in a submodule, any mod whatever; statements inside of there will expect whatever.rs to exist in my_sub_mod/whatever.rs, NOT in the current directory.

You can also do pub mod some_mod;. This will make the module available to parent modules and other crates.

You can also take a private module (declared via mod some_mod;) and publicly re-export it (possibly with a different name) like so:

pub use some::private::module as cool_name;
pub use some::other::private_thing;

That's really all there is to modules.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment