Using sub modules

I've been learning about the Rust module system this weekend. All was going well until I decided to split my sub module to a separate file.

Original: src/lib.rs

pub mod literal {
use crate::literal::sub_literal::MyStruct;

    fn my_fun() {
        let a = MyStruct{num: 43};
    }

mod sub_literal {

    pub struct MyStruct {
        pub num: u32,
    }
}
}

With the mod sub_literal code now in src/literal/sub_literal.rs my use line needs to be, with an extra sub_literal in there.

use crate::literal::sub_literal::sub_literal::MyStruct;

Took me a bit to figure it out. Why the extra layer? Time for another read of the docs no doubt!

mod { … } defines an inline module. There's no need for it if you already have a separate file. Just put the content of the block directly in the file.

I'm sorry, I don't quite understand. I've gone from an inline mod block to using a mod in a separate file and hence the need for the extra level?

No. You still have an inline module but it's now inside another file, which itself is a module. Hence, two layers of modules.

1 Like

Ah! Got it! Removing the mod lines from sub_literal.rs removes the extra layer. Thank you! :smiley:

// mod sub_literal {
    pub struct MyStruct {
        pub num: u32,
    }
// }
``