Search code examples
rustrust-cargo

How to import funnctions in rust from sub directories without using mod.rs


I'm working on a Rust project and I want to organize my code into multiple files and subdirectories. I have a main.rs file that I want to import modules from other files and subdirectories into.

For example, I have a others/utils.rs(in a sub directory of the root dir) and this file has a function, I want to import that function into main.rs, but the thing is I dont want to use the file name as mod.rs, neither i want to move the others/utils.rs out of its sub-directory. I also dont want to wrap the function inside a mod {} or create a mod.rs in others and import the function there and export from there.

How can I declare and import the others/utils.rs module from the others subdirectory into my main.rs file, without using mod.rs or moving the file? I'd like to be able to access the functions and types from utils.rs directly in main.rs.

Can you provide a step-by-step example of how to achieve this?

src/others/utils.rs:-

pub fn get_hello() -> String {
    return "Hello, World!".to_string();
}

ive tried importing fn get_hello like this(main.rs):-

mod others; // results in error, it expects a file `src/others/mod.rs`
use others::get_hello;

Solution

  • So I actually found two methods, which go like this:-

    1]

    mod others { pub mod utils }; // others is the dir, and utils is the file name
    
    use others::utils::get_hello; // use the others/utils.rs file as a module similar to mod.rs
    
    println!("{}", get_hello()); // Hello, World! :)
    

    2]

    #[path = "others/utils.rs"]
    mod utils; // use the utils.rs with directly specifying its path
    
    println!("{}", utils::get_hello()); // Hello, World! :)
    

    Have a nice day.