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?