Search code examples
rustimportrust-crates

How to import a function in main.rs


This may be a stupid question, but I cannot seem to solve this.

I have this kind of file structure:

└── src
    ├── another.rs
    ├── some_file.rs
    └── main.rs

In the some_file.rs, I want to call a function in the main.rs. So, I tried to do something like this in the some_file.rs:

use crate::main


fn some_func() {
   // other code
   
   main::another_func_in_main();
}

But the compiler throws an error:

use of an undeclared crate or module `main`

How can I solve this?


Solution

  • There is no main module, even though you have a main.rs file. The stuff you put in the main.rs file are considered to be at the root of the crate.

    So you have two ways to call the function:

    1. Directly (w/o use)

    crate::another_func_in_main();
    

    2. By importing it first

    use crate::another_func_in_main;
    
    // Then in code, no need for a prefix:
    another_func_in_main();