Although there are plenty of good ones already out there, I started working on a 3D math library as an exercise to jump into Rust called vex. My code is becoming redundant, and I’m not sure on how to go about breaking out the reusable pieces. For example, all three of my vector classes (Vector2
, Vector3
, Vector4
) have a lot of copy and paste code between them. For example, this equality trait implementation is identical across all three classes:
impl cmp::PartialEq for Vector2 {
fn eq(&self, _rhs: &Vector2) -> bool {
for i in 0..2 {
if self[i] != _rhs[i] {
return false;
}
}
true
}
}
I thought about making an internal vector
module contains a bunch of common functionality. Then, each pub Vector
type would import that internal module, and then, for example, all VectorX
s’ operator implementations would just be wrappers for those internal function calls. Does that sound like a good approach? I also thought about implementing traits with default implementation functions making them act like base classes that one would find in an OO language, but I’m not sure if that makes sense, or is even possible since the bulk of these classes involve implementing operator trait implementations as it is.
Is it possible to create a trait that implements multiple other traits? If so, is that even a good idea?
Another question I had was documentation. At first I thought it might be a good rule of thumb to document all public functions, but now I’m thinking that it’s a bit too much. Maybe I shouldn’t have documentation for all vector and matrix operator implementations. Hopefully, I’ve made them obvious enough to where I can just make unit tests in a sub-module at the bottom of the source file for them instead. Thoughts?