-1

I have three files. main.rs, foo.rs, bar.rs all in the src directory. I want to use whats in foo.rs in bar.rs. So i have mod foo; inside of bar. But i get an error as shown below. I do not want to put the foo.rs in a sub directory e.g. src/bar/foo.rs is there another way to structure the code? Because i want foo.rs to be used in many different places besides bar.rs. Optionally if you could tell me how you structure a big project with multiple files then that will suffice.

    file not found for module `foo`
     --> src/bar.rs:1:1
      |
    1 | mod foo;
      | ^^^^^^^^
      |
      = help: to create the module `foo`, create file "src/bar/foo.rs"

    error: aborting due to previous error

main.rs

mod bar;

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

foo.rs

pub fn do_something() {
    
}

bar.rs

mod foo;
dylan
  • 289
  • 2
  • 11

1 Answers1

2

You only have to declare modules once, and in this case you would declare both in main and then you would be able to import them from anywhere else in your codebase using use crate::{mod_name}. Example:

src/main.rs

// declare foo & bar modules
mod foo;
mod bar;

fn main() {
    foo::foo();
    foo::call_bar();
    bar::bar();
    bar::call_foo();
}

src/foo.rs

// import bar module
use crate::bar;

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

pub fn call_bar() {
    bar::bar();
}

src/bar.rs

// import foo module
use crate::foo;

pub fn bar() {
    println!("bar");
}

pub fn call_foo() {
    foo::foo();
}
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98