num-traits icon indicating copy to clipboard operation
num-traits copied to clipboard

Signed trait bounds too restrictive

Open mickvangelderen opened this issue 3 years ago • 1 comments

I am working on a project using uom for quantity and unit aware numeric types.

I have a piece of code that should abstract over Length and Angle and requires the Signed trait from num-traits. However, uom is unable to implement the Signed trait since it requires Num which requires NumOps which requires Mul<Self, Self>. Implementing Mul<Self, Self> for Length is incorrect since the quantity changes to Area.

pub trait Signed: Sized + Num + Neg<Output = Self>
pub trait Num: PartialEq + Zero + One + NumOps
pub trait NumOps<Rhs = Self, Output = Self>:
    Add<Rhs, Output = Output>
    + Sub<Rhs, Output = Output>
    + Mul<Rhs, Output = Output>
    + Div<Rhs, Output = Output>
    + Rem<Rhs, Output = Output>

I would argue the trait bounds on Signed are currently too restrictive. We can work around the problem by defining our own traits but we would rather see this addressed at the root, improving the Rust ecosystem.

For the full discussion, see https://github.com/iliekturtles/uom/issues/273

mickvangelderen avatar Apr 12 '22 12:04 mickvangelderen

It's not something we can immediately change to affect the whole ecosystem -- that would be a breaking change that everyone would have to adapt to.

One thing you could possibly do is create your own Signed and blanket impl from num_traits:

impl<T: num_traits::Signed> Signed for T {
    // your version of methods
}

... and then add additional impl types as needed. However, those extra types must be in the same crate as your Signed definition, so the compiler knows for coherence that they will never add num_traits::Signed and cause overlap.

cuviper avatar Jun 18 '22 00:06 cuviper