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
}
}
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);.
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.