Split main function into multiple files

I have a couple of private modules within my main.rs file. The modules e.g. load the environment variables and start the server. So they contain things which only the main file should see and use.

Now I want to split up the main file into multiple files, but without bringing the files into public scope. How can I do so?

When I extract the modules in separate files, it seems to me that I have to bring the path of the modules in the global scope to be able to use it from the main file. But then any other module can use those modules, although they are only supposed to be used by the main file. how can I make the modules only visible to the main?

  1. No. Modules can be private (and they are by default, unless you explicitly make them pub).
  2. There's no such thing as "the global scope".

Define your main logic in a module then.

mod foo {
    mod bar {}
    mod baz {}    

    pub fn main() {
        println!("Hello");
    }    
}

// can't see `bar` or `baz` here

fn main() {
   foo::main()
}

// Or just use following if you are on latest stable
// use foo::main;

Currently I almost have it like you suggest. The difference is that I have bar and baz not wrapped within foo. In the end I want to have bar and baz in separate files. But this should be possible now as I see your code. i'll try something.

Visibility rules are same regardless of whether the modules are in separate files or inline.

I don't think it's possible to have modules B and C visible from the same module A but not visible from each other.

Edit:

Actually it's possible if you define the modules inside a function:

fn main() {
    #[path="foo.rs"]
    mod foo;
    #[path="bar.rs"]
    mod bar;
}
2 Likes

I now have what I wanted thanks to @zirconium-n's snippet :slight_smile: thank you!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.