Modules in Rust

My project structure looks like this:

src/main.rs
--- game.rs
--- game_state.rs

Inside game.rs has:

mod game_state;

And inside game_state.rs has

mod game;

But this Returns me an error: file not found for module game_state

 0
Author: Klaider, 2018-01-20

3 answers

If you want game.rs and game_state.rs to be in the same root directory as main.rs, you must declare the modules in the main.rs file itself.

// src/main.rs

mod game;
mod game_state;

Modules can only reference submodules if they are directories, so if you declare the submodule mod game_state; in the file game.rs, you must create the directory game/, move the file game.rs to game/mod.rs and create a new file/module game/game_state.rs.

src/game/
    └──── mod.rs
    └──── game_state.rs
src/main.rs

Despite being quite flexible, the module structure of the Rust language is a little confusing and intimidating but there are already discussions that try to improve this situation.

 3
Author: Caio, 2018-06-17 15:53:42

Every file import goes to the main file, i.e. the parent of all:

Main.rs

mod game;
mod game_state;

To refer to game within game_state, you can use:

Game_state.rs

use super::game;

That is, the same as accessing the parent Module (main.rs in fact is a module).

If you want sub-modules similar to main.rs, which can import other files, create a folder, type:

/src/
└── ./game_state/
      └── ./mod.rs
 1
Author: Klaider, 2019-03-22 13:00:48

But this Returns me an error: file not found for module game_state

This structure expects a file at: game_state/game.rs

 0
Author: Erlimar, 2019-05-24 21:07:09