lotsoftools

Understanding Rust Error E0761: Multiple Candidate Files for an Out-of-Line Module

What causes Rust Error E0761?

Rust Error E0761 occurs when multiple candidate files are found for an out-of-line module. It is caused by ambiguity in the module file path, which can happen when there are two files with the same module name but different file extensions, or when a module file is present in both `.rs` and `.rs/mod.rs` format.

Erroneous code example:

// file: ambiguous_module/mod.rs

fn foo() {}

// file: ambiguous_module.rs

fn foo() {}

// file: lib.rs

mod ambiguous_module; // error: file for module `ambiguous_module`
                      // found at both ambiguous_module.rs and
                      // ambiguous_module.rs/mod.rs

How to fix Rust Error E0761?

To fix Rust Error E0761, you need to eliminate the ambiguity by deleting or renaming one of the candidate files. Rust expects a unique path to a module file, so having multiple files for the same module is not allowed.

Solution:

1. Remove or rename the `ambiguous_module/mod.rs` file, or 2. Remove or rename the `ambiguous_module.rs` file.

Examples of valid module structures

Scenario 1: Separate files for each module

// file: module_a.rs

pub fn bar() {}

// file: module_b.rs

pub fn baz() {}

// file: lib.rs

mod module_a;
mod module_b;

pub fn main() {
    module_a::bar();
    module_b::baz();
}

Scenario 2: Nested modules with a directory structure

// file: module_c/mod.rs

pub fn qux() {}

// file: module_c/sub_module.rs

pub fn quux() {}

// file: lib.rs

mod module_c;

pub fn main() {
    module_c::qux();
    module_c::sub_module::quux();
}