Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why rust can't find a function in a submodule? [duplicate]

Tags:

module

rust

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?

like image 955
Eugene Zemtsov Avatar asked Aug 31 '14 08:08

Eugene Zemtsov


1 Answers

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();
}
like image 89
Levans Avatar answered Oct 23 '22 04:10

Levans