Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod.rs and nested modules in Rust

Tags:

rust

I want to specify a generic trait Engine and provide two different implementations: Random and Dummy. I want to use following file structure:

src-
  |-engine
    |-mod.rs //contains Engine trait code
    |-random.rs // contains first engine implementation
    |-dummy.rs // contains second engine implementation

I have something like this in lib.rs:

pub mod engine {
    // random moves engine
    pub mod random;
    pub mod dummy;
}

When I try to add use engine::Engine anywhere in my other modules, it can't be found:

error[E0432]: unresolved import `engine::Engine`
like image 295
GrayR Avatar asked Aug 16 '26 19:08

GrayR


1 Answers

When you write curly braces in a mod item, that tells the compiler that the module's contents are within these braces, not in an external file. Thus, the compiler doesn't even look at engine/mod.rs. When you write a semicolon instead, the compiler will look for an external file.

What you need to do instead is put these lines in engine/mod.rs:

pub mod random;
pub mod dummy;

And in lib.rs, write:

pub mod engine;
like image 76
Francis Gagné Avatar answered Aug 19 '26 22:08

Francis Gagné