Lightsong
Lightsong

Reputation: 345

How to include a public module located in a subfolder

I have the following project where I want to divide some modules into subfolders. The current file structure is simply:

src/
  ->main.rs
  ->cpu/
      ->cpu.rs

main.rs only contains:

fn main() {
    println!("Hello, world!");

    let c : cpu::Cpu;
    cpu::thing();
}

and cpu/cpu.rs contains a struct declaration and a test function:

pub struct Cpu {
    memory : [u8; 16],
}


pub fn thing() -> u8 {
2 // whatever, it's a test
}

How do I include the cpu.rs public functions and structs into main.rs? No matter what I try, I get an error (could not find `cpu` in the crate root) if I use use crate::cpu::{Cpu, thing};, and using mod cpu; seems to only work on the same directory.

Searching for solutions online is extremely infuriating, since the answers are mixed up between the 2015 and 2018 rust editions, are over-complicated or are done in the same folder.

Upvotes: 1

Views: 804

Answers (1)

Netwave
Netwave

Reputation: 42678

You forgot to made cpu (folder) a mod itself, you need to include a mod.rs file in the folder structure:

src/
  ->main.rs
  ->cpu/
      ->mod.rs
      ->cpu.rs

and in mod.rs reexport publicly the inner cpu module:

pub mod cpu;

Upvotes: 1

Related Questions