0

I am trying to do a vector class (mathematical vector, not a storage vector). It can be of dimension DIM, and of type T.

Example : a pixel would be Vector<u32, 2>, a RGBA color would be Vector<f32, 4> (at least in my project)

Here's the definition.

#[derive(Debug, Clone, Copy)]
pub struct Vector<T, const DIM: usize> {
    elements: [T; DIM],
}

impl<T: Default + Copy, const DIM: usize> Vector<T, DIM> {
    pub fn new(elts: [T; DIM]) -> Self {
        Self { elements: elts }
    }
    pub fn null() -> Self {
        Self {
            elements: [T::default(); DIM],
        }
    }
}

Now, if I want to convert a Vec<Ta, DIM> to Vec<Tb, DIM>, I should implement From. But I can not get it to work.

Note that I have a workaround: this cast function works like Into (but Into doesn't work...). (I could use this one just fine but I want to learn what's going wrong).

impl<Ta: Default + Copy, const DIM: usize> Vector<Ta, DIM> {
    pub fn cast<Tb: Default + Copy + From<Ta>>(&self) -> Vector<Tb, DIM> {
    let mut r: Vector<Tb, DIM> = Vector::null();
    for i in 0..DIM {
        r[i] = self[i].into();
    }
    r
}

Here is my definition of From that does not compile:

impl<TypeFrom, TypeTo, const DIM: usize> From<Vector<TypeFrom, DIM>> for Vector<TypeTo, DIM>
where
    TypeFrom: Default + Copy,
    TypeTo: Default + Copy + From<TypeFrom>,
{
    fn from(_: Vector<TypeFrom, DIM>) -> Self {
        todo!()
    }
}

The error is:

conflicting implementations of trait `std::convert::From<optan::core::vector::Vector<_, {_: usize}>>` for type `optan::core::vector::Vector<_, {_: usize}>`
conflicting implementation in crate `core`:
- impl<T> From<T> for T;

Thank you very much for your help

Herohtar
  • 5,347
  • 4
  • 31
  • 41
EloiGG
  • 43
  • 3
  • The error is caused because `TypeFrom` and `TypeTo` could be the same type, so all generics would be identical, conflicting with the blanket `impl From for T`. I'm not sure if there's a workaround. – PitaJ Oct 04 '22 at 21:18

0 Answers0