How can i call a function, existing in another package file, in main function?


#1

Hi, i am new into the Rust’s world !

i have created a project say testproject and the structure of that project is like below -

testproject

  • src
    -package1
    -file1.c
    -package2
    -file2.rs
    -main.rs

Now i want to call a function written in the file2.rs from main.rs. how can i do that ???

i have tried to use mod and use keyword but didn’t work for me.
mod is giving the “Unresolved Module” error


#2

This problem has been solved –

  1. Create a project say test_project and default project tree will be as below -
    test_project
    src
  • main.rs
  1. Create a new package say package1, now tree will look like
    test_project
    src
    • package1
  • main.rs
  1. Now create a rust file say test_file_1 in package1, tree will look like
    test_project
    src

    • package1
      • test_file_1.rs
    • main.rs
  2. Write a test function in test_file_1 and save it.
    Pub fn test_fun() {
    println!(“Test function executed successfully !!”)
    }

  3. Create a new file in the package1 named mod.rs and declare the rust file which you want to call -
    mod.rs :
    pub mod test_file_1;

after this tree will look like below -
src

  • package1
    • mod.rs
    • test_file_1.rs
  • main.rs
  1. Now call the fun in main like below -
    main.rs:

mod package1;
fn main() {
package1::test_file_1::test_fun();
}

Note: if you will try to call the function, written in test_file_1, directly from main, without creating the mod.rs then rust compiler will give the error saying “Unresolved Import”