lotsoftools

Understand and Resolve Rust Error E0659: Ambiguous Item Usage

Understanding Rust Error E0659

Rust Error E0659 occurs when the same name is used for two different items in the same scope, making it ambiguous. This often happens when you import items with the same name from multiple modules into the current scope. The error message indicates that the compiler is unable to determine which one of the items you are referring to.

Code Example That Triggers E0659

pub mod moon {
    pub fn foo() {}
}

pub mod earth {
    pub fn foo() {}
}

mod collider {
    pub use crate::moon::*;
    pub use crate::earth::*;
}

fn main() {
    crate::collider::foo(); // ERROR: `foo` is ambiguous
}

In this example, we have two modules, moon and earth, with a function named foo() in each. We import these functions into the collider module using the wildcard syntax (*). Now, when we try to call crate::collider::foo(), the compiler raises an E0659 error because it cannot determine which foo() function we want to call.

Resolving Rust Error E0659

To fix Rust Error E0659, you need to provide a more explicit path or use aliases when importing items with the same name. By doing so, you avoid ambiguity and make it clear to the compiler which item you want to access.

Method 1: Keep the path before the item

Instead of importing the items directly using *, you can import the entire modules and use the full path when calling the functions:

pub mod moon {
    pub fn foo() {}
}

pub mod earth {
    pub fn foo() {}
}

mod collider {
    pub use crate::moon;
    pub use crate::earth;
}

fn main() {
    crate::collider::moon::foo(); // ok!
    crate::collider::earth::foo(); // ok!
}

Method 2: Use aliases for import

Another way to resolve the error is to use aliases when importing the items. Here's an example:

pub mod moon {
    pub fn foo() {}
}

pub mod earth {
    pub fn foo() {}
}

mod collider {
    pub use crate::moon::foo as moon_foo;
    pub use crate::earth::foo as earth_foo;
}

fn main() {
    crate::collider::moon_foo(); // ok!
    crate::collider::earth_foo(); // ok!
}

In this example, we use aliases moon_foo and earth_foo for the imported functions, which resolves the ambiguity.