lotsoftools

Rust Error E0118: Inherent Implementation for Invalid Types

Understanding Rust Error E0118

The error code E0118 occurs in Rust when you attempt to define an inherent implementation for an invalid type. Essentially, you've used the 'impl' keyword to define methods for a type that isn't a struct, enum, union, or trait object.

Causes of Rust Error E0118

This error occurs when you try to use the 'impl' keyword to implement methods directly on a generic type parameter (T) instead of on a nominal struct, enum, union, or trait object. The following code exemplifies the erroneous usage:

#![allow(unused)]
fn main() {
  impl<T> T { // error: no nominal type found for inherent implementation
    fn get_state(&self) -> String {
        // ...
    }
  }
}

Fixing Rust Error E0118

To resolve this error, you need to either implement a trait on the type or wrap it in a struct.

1. Implementing a Trait

To implement a trait on the type, define a trait that includes the desired method and then implement the trait for the type T as follows:

#![allow(unused)]
fn main() {
  // we create a trait here
  trait LiveLongAndProsper {
    fn get_state(&self) -> String;
  }

  // and now you can implement it on T
  impl<T> LiveLongAndProsper for T {
    fn get_state(&self) -> String {
        "He's dead, Jim!".to_owned()
    }
  }
}

2. Creating a Newtype

Alternatively, you can create a newtype, which is a wrapping tuple-struct. This involves defining a wrapper struct with the generic type parameter and implementing the desired method on the wrapper struct:

#![allow(unused)]
fn main() {
  struct TypeWrapper<T>(T);

  impl<T> TypeWrapper<T> {
    fn get_state(&self) -> String {
        "Fascinating!".to_owned()
    }
  }
}