Conflict when implementing trait using &T and &[T; N]

I'm trying to implement tryfrom for reference and array reference but it seems like I'm doing something wrong here:

error[E0119]: conflicting implementations of trait data::alloc::TryFrom<&[_; _]> for type data::alloc::Alignment
--> src\data\alloc.rs:43:1
|
19 | impl<T, const N: usize> self::TryFrom<&[T; N]> for Alignment {
| ------------------------------------------------------------ first implementation here
...
43 | impl self::TryFrom<&T> for Alignment {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for data::alloc::Alignment

apparently rust is treating &T and &[T; N] as the same type.
The code compiles if I change the array reference to a slice &[T].

What can I do to fix this?

The generic parameter T is any Sized type, including array types. It doesn't include slice types because slice types are not Sized.

You will have to either:

  • Add bounds to your TryFrom<&T> implementation such that [U; N] doesn't match
  • Implement TryFrom<&SomeMoreSpecificType<T>> instead
  • Arrange so that your TryFrom<&T> implementation is also suitable when T is an array type, so you only need one type.

This may involve redesigning your trait. It will help if you share your code and what you are trying to achieve, not just the error.

2 Likes

Think of it as if the two types are &T and &[U; N]. They are defined in different impls and there's nothing that links the two Ts. At this point try to answer the question whether they can be the same type, and they sure can if T = [U; N]!

4 Likes