13

I'm trying to call a function from a module located in a separate file, the function is public and I am calling it using a full path, but rustc still complains about "unresolved name".

a.rs

pub mod b;
fn main() {
  b::f()
}

b.rs

pub mod b {
    pub fn f(){
        println!("Hello World!");
    }
}

compilation

$ rustc a.rs
a.rs:3:5: 3:9 error: unresolved name `b::f`.

When I move the module to the crate's main file, everything works fine.

one_file.rs

pub mod b {
    pub fn f(){
        println!("Hello World!");
    }
}
fn main() {
    b::f()
}

Aren't these two ways supposed to be equivalent? Am I doing something wrong, or it's a bug in rustc?

Eugene Zemtsov
  • 355
  • 1
  • 3
  • 7

1 Answers1

23

When you have separate files, they are automatically considered as separate modules.

Thus, you can do :

othermod.rs

pub fn foo() {
}

pub mod submod {
    pub fn subfoo() {
    }
}

main.rs

mod othermod;

fn main ()  {
    othermod::foo();
    othermod::submod::subfoo();
}

Note that if you use sub-directories, the file mod.rs is special and will be considered as the root of your module :

directory/file.rs

pub fn filebar() {
}

directory/mod.rs

pub mod file;

pub fn bar() {
}

main.rs

mod directory;

fn main() {
    directory::bar();
    directory::file::filebar();
}
Levans
  • 14,196
  • 3
  • 49
  • 53