num-derive
num-derive copied to clipboard
num_derive for newtypes
From @gnzlbg on October 26, 2017 9:18
Say I want to implement some num traits for:
struct R64(f64);
Is there a macro in num_derive
to do this? Currently FromPrimitive and ToPrimitive only work on enums.
Copied from original issue: rust-num/num#341
Those FromPrimitive
and ToPrimitive
derivations for enums are all we have right now. I would be fine with adding newtype derivations though!
From @termoshtt on October 27, 2017 6:53
I think proc_macro is better.
I've created a NewType derivation in my crate which derives From
, Deref
, and DerefMut
. IMO, #[derive(Num)]
should derive Add
, Sub
, Mul
, Div
, and Rem
which is required by NumOps
(not Num
). Remaining traits, i.e. One
and Zero
should be separated. Hence the interface becomes:
#[derive(One, Zero, Num, PartialEq)]
struct R64(f64);
What do you think?
From @gnzlbg on October 27, 2017 7:5
I am writing a derive_ops
crate where you can do this:
#[derive(stdops)]
#[unary_ops(Not, Neg, Deref, ...)]
#[binary_ops(Add = "Self", Add = "f64", Index = "usize")]
struct R64(f64);
to specify exactly what you want to derive.
It then builds on this to support ops groups:
[derive(stdops)]
[numops]
[binary_ops(DivAssign = "Self")]
struct R64(f64);
If you want I can commit it and maybe we can collaborate. The idea is to derive all ops in stdops
for tuple structs with one element easily.
From @termoshtt on October 27, 2017 7:15
It looks great :) Does it work on stable rust? I think it will be an independet crate since it will be useful in several cases.
From @gnzlbg on October 27, 2017 7:19
It works on stable rust (uses only custom derive). Yes I intended it as a separate crate because I think it is generally useful.
As far as num-derive goes, I was only thinking of derivations for num's own traits. For more general stuff, see also derive_more.
From @gnzlbg on October 27, 2017 8:7
derive_more
doesn't support deriving Mul<R64> for R64
by design. It only supports Mul<f64> for R64
.