0

Project structure is as -

enter image description here

and foo.rs is as-

pub mod Foo {
    pub fn work() {
        println!("Test executed.");
    }
}

main.rs is simple as -

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

now how to call work function in main function?

I have tried with -

  • use crates::modals::Foo; not working
  • adding mod.rs in modals not working
  • adding modals.rs at main.rs level not working

What are the right and simple ways to do this?

Amber More
  • 131
  • 1
  • 15

1 Answers1

-1

You also need a src/lib.rs:

pub mod modals;

Then a src/modals/mod.rs instead of src/modals/foo.rs, though you could have in that:

pub mod foo;

Then to import it into main.rs:

use cratename::modals::Foo;

Where cratename is the name = property in your Cargo.toml.

Unlike other more free-form languages, Rust has significant constraints on how you name and organize your files.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • So in this case what will be main.rs code? – Amber More Jul 04 '20 at 17:40
  • But with that statement I am getting unresolved import `crate::modals` – Amber More Jul 04 '20 at 17:44
  • I have added lib.rs, mod.rs and kept foo.rs as it is. – Amber More Jul 04 '20 at 17:45
  • Make sure you have a `mod.rs` in each "module" directory, and that your `Cargo.toml` defines a crate, which it might not. – tadman Jul 04 '20 at 17:45
  • No luck, refer this too https://stackoverflow.com/questions/45519176/how-do-i-use-or-import-a-local-rust-file but no luck – Amber More Jul 04 '20 at 18:12
  • 1
    Modules are declared starting at a crate entry point. Either `lib.rs` or `main.rs` can be an entry point but not both. You can make it work, but it is far more confusing and only necessary when you want the crate to be _both_ a binary and a library. – Peter Hall Jul 04 '20 at 19:01