1

I have two modules (in their own files) that both try to use a third, only one of them finds the file the third is in though.

Why does the order of the mod-statements in main.rs matter? If I remove all the "bar-stuff" then the problem still remains.

main.rs

mod foo;
mod bar;
fn main() {
    foo::do_foo();
    bar::do_bar();
}

foo.rs

mod foo_bar; // error will be here when "mod foo;" is first in main.rs
pub fn do_foo() {
    println!("foo::");
    foo_bar::do_foo_bar();
}

bar.rs

mod foo_bar; // error will move to here when putting "mod bar;" first in main.rs instead
pub fn do_bar() {
    println!("bar::");
    foo_bar::do_fo_bar();
}

foo_bar.rs

pub fn do_foo_bar() {
    println!("foo_bar");
}
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Jarsefax
  • 11
  • 2
  • 2
    I think you're misinterpreting the messages: *neither* `foo.rs` nor `bar.rs` can find the module named `foo_bar`. The compiler only gets as far as the first missing module before giving up, which is why rearranging the `mod` statements in `main.rs` changes which file you get the error from. – trent Jun 28 '19 at 16:23
  • I think you're saying `mod` when you mean to say `use` -- it may be a bit confusing because `mod` automatically `use`s -- but there should only ever be one `mod` for a given module, because the placement of the `mod` determines where the module fits in the hierarchy. If you change the `mod foo_bar;`s to `use foo_bar;` and put a `mod foo_bar;` in either lib.rs or main.rs, it should work. I can't test it now, unfortunately. – trent Jun 28 '19 at 16:29
  • [Can't understand Rust module system](https://stackoverflow.com/q/37610079/3650362) may be a question that helps you understand how this works. – trent Jun 28 '19 at 16:30
  • @trentcl If I do `mod foo_bar;`in `main.rs` and `use foo_bar;` in `main.rs` as you suggested then the compiler complains that I can't use foo_bar because it is not an external crate. So that did not work. – Jarsefax Jun 28 '19 at 22:25
  • But `use crate::foo_bar;` did work. Thank you @trentcl – Jarsefax Jun 28 '19 at 22:31

0 Answers0