0
votes

I have a small Rust project, and would like the simplicity of a flat module system, combined with the modularity of separate files. In essence, I would like this program:

src/main.rs

fn print_hello_world() {
    println!("Hello, world!");
}

fn main() {
    print_hello_world();
}

to be structured akin to this:

src/print_hello_world.rs

pub fn print_hello_world() {
    println!("Hello, world!");
}

src/main.rs

use crate::print_hello_world; // Error: no `print_hello_world` in the root

fn main() {
    print_hello_world();
}

Note that there is only a single module in this pseudo project; the crate root module. No child modules exists. Is it possible to structure my project like this? If yes, how?

Solution attempts

It is easy to get this file structure by having this:

src/main.rs

mod print_hello_world;
use print_hello_world::print_hello_world;

fn main() {
    print_hello_world();
}

but this does not give me the desired module structure since it introduces a child module.

I have tried finding the answer to this question myself by studying various authorative texts on this matter, most notably relevant parts of

My conclusion so far is that what I am asking is not possible; that there is no way to use code from other files without introducing child modules. But there is always the hope that I am missing something.

1

1 Answers

1
votes

This is possible, but unidiomatic and not recommended, since it results in bad code isolation. Making changes in one file is likely to introduce compilation errors in other files. If you still want to do it, you can use the include!() macro, like this:

src/main.rs

include!("print_hello_world.rs");

fn main() {
    print_hello_world();
}