lotsoftools

Rust Error E0428: Duplicate Type or Module

Understanding Rust Error E0428

Rust Error E0428 occurs when a type or module has been defined more than once in the same scope. This error can be caused by accidentally duplicating a type or module, or by importing the same type or module multiple times.

To resolve Rust Error E0428, verify the names of the types and modules, remove any duplicates, or give them unique names.

Example of Erroneous Code

#![allow(unused)]
fn main() {
struct Bar;
struct Bar; // error: duplicate definition of value `Bar`
}

In the erroneous code example above, the struct 'Bar' is defined twice, causing Rust Error E0428. To fix the error, the duplicated type should be removed or renamed.

Example of Corrected Code

#![allow(unused)]
fn main() {
struct Bar;
struct Bar2; // ok!
}

In the corrected code example above, the second struct 'Bar' has been renamed to 'Bar2', so there are no duplicate types and the code will compile successfully.

Avoiding Imports with Same Name

Rust Error E0428 can also occur when importing the same type or module multiple times. To avoid this error when using imports, ensure that each type or module is imported only once, or use the 'as' keyword to rename the imported type or module.

Example of Imports with Same Name

mod foo {
pub struct Bar;
}

mod baz {
pub struct Bar;
}

use foo::Bar; // imported from foo
use baz::Bar; // error: duplicate import of `Bar`

In the import example above, Rust Error E0428 occurs because the struct 'Bar' is imported from both 'foo' and 'baz' modules. To resolve the error, use the 'as' keyword to rename one of the imports.

Example of Corrected Imports

mod foo {
pub struct Bar;
}

mod baz {
pub struct Bar;
}

use foo::Bar; // imported from foo
use baz::Bar as Bar2; // ok! different name for the imported struct

In the corrected imports example above, the struct 'Bar' from the 'baz' module has been renamed to 'Bar2' using the 'as' keyword, avoiding the duplicate import error.