Reputation: 48058
I have a vector with an add
operator:
use std::ops::Add;
struct float2(f64, f64);
impl Add for float2 {
type Output = float2;
fn add(self, _rhs: float2) -> float2 {
float2(self.0 + _rhs.0,
self.1 + _rhs.1)
}
}
Is it possible to write this in such a way that it would work for a 3D or 4D vector too?
e.g.: struct float2(f64, f64, f64);
I managed to add an Index
operator, and a len
method that returns a static value for each type, but this feels a bit cumbersome. I didn't check the assembly, but its possible all index accesses are checked, which seems unnecessary for such a low level operation.
I could also pack the struct and use direct unsafe memory access, but this also doesn't seem very optimal.
Is there a more convenient way to write expressions that handle all elements of the struct?
Upvotes: 2
Views: 257
Reputation: 430673
No, it is not possible. What is possible is writing code that will write the code needed. This is known as metaprogramming. In Rust, there are two main avenues for metaprogramming: build scripts and macros. Compiler plugins also exist, but are much more complicated.
The Rust standard library uses macros to implement traits for arrays and tuples from 0 to 32, so it's certainly an accepted pattern. You should start by writing out a few cases to see how each iteration differs, then extract a macro from that.
Further reading:
Upvotes: 2