0

MyClass is just a byte array. Since I want flexible conversions to and from MyClass, I implemented From as From<T> for MyClass where T: AsRef<[u8]>. This works, but as soon as I implement the corresponding AsRef<[u8]> for MyClass I get an "conflicting implementations" error.

use std::convert::{AsRef, From};

const MY_SIZE: usize = 32;

pub struct MyClass(pub [u8; MY_SIZE]);

impl AsRef<[u8]> for MyClass {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl<T> From<T> for MyClass
where
    T: AsRef<[u8]>,
{
    fn from(byteable: T) -> Self {
        let bytes: &[u8] = byteable.as_ref();
        assert_eq!(bytes.len(), MY_SIZE);
        let mut dst: [u8; MY_SIZE] = [0; MY_SIZE];
        dst.copy_from_slice(&bytes);
        MyClass(dst)
    }
}

fn main() {}
error[E0119]: conflicting implementations of trait `std::convert::From<MyClass>` for type `MyClass`:
  --> src/main.rs:13:1
   |
13 | / impl<T> From<T> for MyClass
14 | | where
15 | |     T: AsRef<[u8]>,
16 | | {
...  |
23 | |     }
24 | | }
   | |_^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> std::convert::From<T> for T;

Can I avoid the error or is there a better way to design this library?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Manuel Schmidt
  • 2,429
  • 1
  • 19
  • 32
  • TL;DR the duplicates: It's now ambiguous what code should be invoked when you call `From::from(MyClass)` — should it be the code in this crate of the blanket implementation from the standard library. This ambiguity is not allowed. – Shepmaster Jan 17 '18 at 14:12
  • But if I remove my AsRef, I cannot call From on my class. So there is NO implementation left, if remove mine. – Manuel Schmidt Jan 17 '18 at 15:41
  • *there is NO implementation left, if remove mine.* — sure there is: [`impl From for T`](https://doc.rust-lang.org/std/convert/trait.From.html). That's the one that the compiler is telling you about: *`note: conflicting implementation in crate \`core\`: - impl std::convert::From for T;`* – Shepmaster Jan 17 '18 at 16:13

0 Answers0