Using modules leads to mismatched types


#1

I have a couple of files in src directory. Until now, using functions and structs from other file ment that I had to use this line (a plain mod does not work):

#[path = "file1.rs"] mod file1;

Now, when I’m starting to link everything, I am having problems understanding this mods. For example, lets say I have three files:

file1.rs:

struct Foo {...}

file2.rs:

#[path = "file1.rs"] mod file1;
pub fn bar(f: &file1::Foo) {...}

file3.rs:

#[path = "file1.rs"] mod file1;
#[path = "file2.rs"] mod file2;
...
let v = file1::Foo(...);
file2::bar(&v);

Trying to compile this, leads to next error:

error: mismatched types:
expected '&file2::file1::Foo',
found '&file1::Foo'

This is just an example. I do have a good enough reason, for why I am having different things in different files. So what am I doing wrong here?


#2

By using mod file1 both in file2 and file3, you actually create 2 modules file2::file1 and file3::file1, both using the code from file1.rs - similar, but different…

The error message leaves out the current module, the full would be:

error: mismatched types:
expected '&file2::file1::Foo',
found '&file3::file1::Foo'

You may want to use the module file1 in both file2 and file3. (this reads a bit bad with this font: use is a keyword).


#3

Did you read the book chapter on Crates and Modules? It explains how mod is used to define modules and they are defined only once per crate.


#4

As skade said, you’re creating multiple versions of file1.

Try declaring all mods regularly in a lib.rs file, like:

mod file1;
mod file2;
mod file3;

Then, in file2 and file3, just use use file1 instead of declaring it as a mod:

file2.rs:

use file1;

pub fn bar(f: &file1::Foo) {...}

file3.rs:

use file1;
use file2;
...
let v = file1::Foo(...);
file2::bar(&v);