Modules in Rust

0

The structure of my project looks 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 gives me an error: file not found for module game_state

    
asked by anonymous 20.01.2018 / 22:35

2 answers

1

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.

// src/main.rs

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

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

Although very flexible, the Rust language module structure is a bit confusing and intimidating but there are already discussions that try to improve this situation.

    
07.02.2018 / 19:00
0

You can only import modules of files within the module of your main file ( main.rs , lib.rs or mod.rs generally), as Caio said. This basically means that to use both game.rs and game_state.rs you should import game.rs and game_state.rs all through main.rs :

main.rs

// Importa game.rs ou game/mod.rs
mod game;

// Importa game_state.rs ou game_state/mod.rs
mod game_state;

The Rust compiler sees the structure of the modules in a very different way from C # ( csc ) and other languages out there. Let's reflect a bit ... main.rs belongs to a module, the root of your crate, but all other rs files, divergent from the main file, main.rs , belong to the child modules or children of children. To access a statement from the parent module you use super::Decl , for example, let's assume that ...

  • main.rs has a struct Global ,
  • The module that main.rs belongs to is the relative of the module to which game.rs belongs and
  • which game.rs uses the struct Global of main.rs .

main.rs

pub struct Global {}
mod game;

game.rs

use super::Global;

// Sinta-se livre para usar a struct Global
// pelo game.rs inteiro.

This is an example of how to use parent module declarations. However, to use child modules, you always need self:: , because what you type in a use statement is absolute path to the root module of your crate, ie, that code would not work there:

main.rs

mod game;
use game::Shared; // Falha, pois 'game' não existe
                  // na sua crate.

game.rs

pub struct Shared {}

Here you should use use self::game::Shared instead of game::Shared . And I think that's enough to understand Rust's modules.

    
20.10.2018 / 01:27