derive_more
derive_more copied to clipboard
Pointwise addition (and multiplication) for array struct members?
Could we make point-wise addition (and multiplication etc) work for structs (and enums etc) that contain arrays as well?
#[derive(Add)]
struct<T> MyStruct {
x: [T; 32],
y: T,
}
At the moment, this fails.
We have a similar failure for tuples:
#[derive(Add)]
struct PointArray {
a: i32,
xy: (i32, i32),
z: i32,
}
@matthiasgoergens the tuple case (i32, i32) seems OK, but I'm unsure about the array case [T; 32]. It's not obvious why the Add semantics on array is by-element adding, and not the arrays concatenation.
@JelteF what do you think on this?
tl;dr +1 on the idea
Concatenation seems impossible to do to me without returning a different type from Add. So while I also think concatenation is an equally valid Add implementation, I don't think that one could ever be achieved by using derive_more. So having the element-wise addition, seems fine.
And even if we ever figured out how to implement concatenation, we could still add a special attribute to choose between the two.
Yes, because of the types, point-wise addition is the only thing that makes sense for fixed length arrays.
Have a look at the linked PR for an implementation prototype (with some caveats as noted in my comment.)
Perhaps going with the initial approach, but explicitly adding a Copy constraint in the impl, when the struct contains an array, might be fine? Copy is pretty much mandatory for using Add and Mul etc anyway.