Conflicting implementations of trait `X` for type `u8`

I have custom type which inherits standard type. I want to impl trait on it, but got an error:

error[E0119]: conflicting implementations of trait `Test` for type `u8`
  --> src/main.rs:13:1
   |
7  | impl Test for u8 {
   | ---------------- first implementation here
...
13 | impl Test for CustomType {
   | ^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `u8`

For more information about this error, try `rustc --explain E0119`.

this is my code:

type CustomType = u8;

trait Test {
    fn test(&self) -> &Self;
}

impl Test for u8 {
    fn test(&self) -> &Self {
        self
    }
}

impl Test for CustomType {
    fn test(&self) -> &Self {
        self
    }
}

This is sandbox.

Could somebody explain how to fix this ?

type CustomType = u8 just defines a new name for u8 - it is not actually a distinct type. Make a unit struct wrapping a u8 if you want that behavior: struct CustomType(u8);.

4 Likes

Thank you !

Also note that there is no inheritance in Rust, and types are not classes.

1 Like

I trying to do this:

struct CustomType(u8);

impl Test for CustomType {
    fn test(&self) -> &Self {
        let (value) = self;
        // ...
    }
}

but seems like value is not u8, it's CustomType. Could you tell how can I get u64 from this TupleStruct ?

(edited according to code example above)

yep, I just mean I want CustomType to be just u8, but implement another behavior (different from what I implemented on u8 already).

Found solution. Need to do next:

let value = self.0;

If you want to use a destructuring pattern then you need to do let CustomType(value) = self;

1 Like

I think it's better to do #[repr(transparent)] struct CustomType(u8);. This guarantees that the layout of your custom type is the same as u8.

Otherwise it may become, e.g., 32-bit on some strange platform where byte access is inefficient. Plus #[repr(transparent)] tells the reader that what you want is just a wrapper, not a tuple which happens to be single-element one currently.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.