Unable to declare module "cannot declare a new module at this location"

I have 3 files: lib.rs, file2.rs and file3.rs. I am lib.rs I have this:

mod file2; use file2::Struct2; 

and it works well. However, the same thing in file3 compiles with an error:

 mod file2; use file2::Struct2; => error: cannot declare a new module at this location 

And if I remove the mod file2 declaration, I get the following:

 error: unresolved import `Struct2` 

What happened to this?

+4
source share
1 answer

I'm not sure why you are getting this error for sure, but it won’t do what you want. Modules form a tree structure, and you use mod declarations to form them. So you are trying to create another mod2 in file3.

I assume that you want the files file2 and file3 to be under the main module, and not with additional modules of each other. To do this, put

 mod file2; mod file3; 

In lib.rs and then in file3.rs

 use file2::Struct2; 

And everything should work. I am on a mobile phone, so I can’t check myself three times, sorry for the formatting.

+7
source

All Articles