Monday, May 15, 2023

Rust Modules


In this post we review how to organize a big project into modules and files.

Let review the files structure:




We have two root standard files: The main.rs is the binary starting point and the lib.rs is the library starting point. We can have both, so the crate can be used both as binary and as library.


Each module should (but not must) exists in it own file. Sub modules should be in a sub folder named after their parent module. We have a module named another_game, and its sub module named player.


Let's review usage of the modules in the main.rs file.




First we can see a module within the main.rs, and not in it own file. This is a bad practice, but is possible.

We can access the modules using relative path and absolute path. Looks like the relative path is the more sensible method. A relative path can also access its parent using the super keyword. 

Anything that we want to access from outside the module must be defined as public. Notice that for structs, in case not all the fields are public, we cannot instantiate them, so we must supply a constructor function. Notice that to access an item from outside its module, we must have all the route from the accessing point to the item public.


Let view some of the module code in another_game.rs:




Here again we see the public keyword wherever we want to provide public access. We can see that a struct can have some of its fields public, and some private.







No comments:

Post a Comment