Why can't rust find a function in a submodule?

I am trying to call a function from a module located in a separate file, the function is public, and I call it using the full path, but rustc still complains about the "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 main file of the box, everything works fine.

one_file.rs

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

Shouldn't these two paths be equivalent? Am I doing something wrong, or is it a mistake in rustc?

+5
source share
1 answer

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

So 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(); } 

Please note that if you use subdirectories, the mod.rs file 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(); } 
+10
source

Source: https://habr.com/ru/post/1201493/


All Articles