lotsoftools

Understanding Rust Error E0390

Rust Error E0390: Overview

Rust Error E0390 occurs when a method or constant is implemented on a primitive type instead of utilizing a trait to define the function. This can be resolved by moving the reference inside the implementation under a trait or by defining an inherent implementation on a reference.

Erroneous Code Example

struct Foo {
    x: i32
}

impl *mut Foo {}
// error: cannot define inherent `impl` for primitive types

Solution 1: Using a Trait

A recommended approach is to implement a trait to define the method or constant. Here's an example of how to refactor the erroneous code using a trait:

struct Foo {
    x: i32
}

trait Bar {
    fn bar();
}

impl Bar for *mut Foo {
    fn bar() {} // ok!
}

Solution 2: Moving the Reference

An alternative solution is to move the reference inside the implementation. This can be achieved by refactoring the code like this:

Original code:

struct Foo;

impl &Foo { // error: no nominal type found for inherent implementation
    fn bar(self, other: Self) {}
}
Refactored code:

struct Foo;

impl Foo {
    fn bar(&self, other: &Self) {}
}

Conclusion

To resolve Rust Error E0390, avoid implementing methods or constants directly on a primitive type. Instead, refactor the code by using a trait to implement the functionality or moving the reference inside the implementation. This article demonstrated both solutions with code examples to help you better understand and handle this error.