Crate compiled multiple times and type with similar name

Hi!

I'm stuck from several times with the following problem:

cargo check --bin battle_gui
error[E0308]: mismatched types
   --> battle_gui/src/run.rs:104:49
    |
104 |             return Err(GuiError::EmbeddedServer(error));
    |                        ------------------------ ^^^^^ expected `EmbeddedServerError`, found `server::EmbeddedServerError`
    |                        |
    |                        arguments to this enum variant are incorrect
    |
    = note: `server::EmbeddedServerError` and `EmbeddedServerError` have similar names, but are actually distinct types
note: `server::EmbeddedServerError` is defined in the current crate
   --> battle_gui/src/server/mod.rs:19:1
    |
19  | pub enum EmbeddedServerError {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: `EmbeddedServerError` is defined in crate `battle_gui`
   --> /home/bastiensevajol/Projets/OpenCombat2/battle_gui/src/server/mod.rs:19:1
    |
19  | pub enum EmbeddedServerError {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    = note: the crate `battle_gui` is compiled multiple times, possibly with different configurations
note: tuple variant defined here
   --> /home/bastiensevajol/Projets/OpenCombat2/battle_gui/src/lib.rs:40:5
    |
40  |     EmbeddedServer(EmbeddedServerError),

I understand error kind, but, I don't understand where I compile it multiple time. This is from an open source project, so you can find sources here (branch "examples") : GitHub - buxx/OpenCombat at examples

I use workspace and import different workspace crates. Here, battle_gui import some other but EmbeddedServerError is defined and used only in battle_gui.

In error message, I can see type is the same but displayed as two different paths:

--> battle_gui/src/server/mod.rs:19:1
--> /home/bastiensevajol/Projets/OpenCombat2/battle_gui/src/server/mod.rs:19:1

Any idea ? Thanks !

It's generally not useful to have the same mod xyz; declared in both lib.rs and main.rs - that's where the duplication is coming from. I would delete all the mod xyz; statements in main.rs.

Cargo allowing library and binaries to share the same directory structure is a common footgun that beginners run into. To make things simple for yourself, do not write any mod xyz; statements in main.rs at all - import whatever you need from the library crate with use battle_gui::xyz; instead.

Work like a charm. Thanks for explanation !

Another approach to reduce confusion is to use the src/bin/ file layout, usually used for multiple binaries but always an option:

battle_gui/
    Cargo.toml
    src/
        lib.rs
        some_mod_of_lib.rs
        bin/
            battle_gui/
                main.rs
                some_mod_of_main.rs
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.