How to use functions from different folders under crate root?

Under my src folder, I have two subdirectories called renderhd, and render4k. I have a main.rs (obviously!) from which I want to call render4k/lowthreaded.rs

How can this be achieved without moving everything into the src root?

In your src/main.rs, declare modules for each of your subdirectories:

mod renderhd;
mod render4k;

Then Rust will look for either src/render4k.rs or src/render4k/mod.rs (and similar for renderhd); I prefer using src/render4k.rs. In that file, declare modules for the files in your subdirectories, so src/render4k.rs will declare modules for each of the files in src/render4k/. These modules need to be public, like so:

pub mod lowthreaded;

If src/render4k/lowthreaded.rs contains a public function like:

pub fn foo() {
    println!("foooo");
}

Then in src/main.rs, you can call it with:

fn main() {
    render4k::lowthreaded::foo();
}

Chapter 7 of the book has more info on all of this :slight_smile:

4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.