#Implementing From on a struct that takes a const generic usize

8 messages · Page 1 of 1 (latest)

old island
#

I'm looking to be able to do something like this:

impl<const N: usize, const W: usize> From<Num<W>> for Num<N> where N != W

This isn't valid syntax, but I would assume something similar exists. I tried:

impl<const N: usize, const W: usize> From<Num<W>> for Num<N>

But that gets a:
```error[E0119]: conflicting implementations of trait std::convert::From<Num<_>> for type Num<_>

#

Where the num struct is just:

pub struct Num<const N: usize> { /* implementation */ }
dense eagle
#

You can do the thing you want

impl<const N: usize, const M: usize> From<Num<N>> for Num<M>
where
    [(); not_equal(N, M)]:,
{
    fn from(_value: Num<N>) -> Self {
        todo!()
    }
}

const fn not_equal(n: usize, m: usize) -> usize {
    if n == m {
        panic!("numbers were equal")
    }
    0
}
```but it doesn't help because you can't avoid conflicting implementations by putting stuff in a where clause.
old island
#

Would this be a place where tryfrom is necessary?

dense eagle
#

No, you can't implement that for the same reason

#

You could use a different trait, or implement it for specific numbers

old island
#

Specific numbers won’t work, so I guess I’ll try implementing a trait I define with a similar API

old island
#
pub trait NumFrom<const N: usize, const W: usize> {
    type S;
    fn convert(other: Self::S) -> Self;
}

impl<const N:usize, const W:usize> NumFrom<N, W> for Num<N> {
    type S = Num<W>;
    fn convert(other: Num<W>) -> Num<N> {
        todo!()
    }
}