Modules in Rust

Asked

Viewed 237 times

2

The structure of my project is like this:

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

Within game.rs has:

mod game_state;

And within game_state.rs has

mod game;

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

3 answers

5

If you wish to game.rs and game_state.rs stay in the same root directory of main.rs, you must declare the modules in the file itself main.rs.

// src/main.rs

mod game;
mod game_state;

Modules can only reference sub-modules if they are directories, so if you declare the sub-module mod game_state; in the archive game.rs, you need to create the directory game/, move the file game.rs for 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 bit confusing and intimidating but there is already discussions who try to improve this situation.

1

All file import goes to the main file, ie the relative of all:

main rs.

mod game;
mod game_state;

To refer to game inside game_state, can use:

game_state.rs

use super::game;

That is, the same of 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, like:

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

0

But this returns an error: file not found for module game_state

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.