I am trying to implement a linear algebra library in zig for learning purposes, and i want to create structs for vectors of different sizes like Vector2, Vector3, Vector4. The problem is that all of them share the exact properties and functions and i want to know the best way to do this efficiently. Should i rewrite the functions for every vector type or should i just make a generic vector of variable length? Most importantly is there a 'zig' way to do something like this?
#Need suggestions on how to implement multiple structs which share extremely similar functions
1 messages · Page 1 of 1 (latest)
Need suggestions on how to implement multiple structs which share extremely similar functions
I think that a Vector struct generic on the length is the best option
If they need to be in the same container, they do need to be the same type
So yeah, either runtime known length or you can use function pointers
Not sure which would be better
Dynamic length would probably have the least code duplication but it wouldnt be as flexible
But you probably dont need any flexibility here
i guess i will go with that for now, maybe i just got a nice idea to use comptime
You can still use comptime and then give the user the option to convert it to a type erased dynamic one
Stdlib does this with GenericWriter
It just has a any() method that returns a type erased AnyWriter
do you need the ability to hold a value that is a vector of runtime known length?
as in, should this work:
var v = Vector2.new(...);
v = Vector3.new(...);
// or however you're making your API...
i shall check GenericWriter then
the problem i have is quite different than the one you are talking about. I wanted to know whether i should repeatedly write very similar functions for all vector types, or rather make a vector type which can be of any dimensions/length instead of having seperate Vector2, Vector3, etc
It should be pretty intuitive to implement
Just give each generic vector a method that returns a dynamic vector of the same length and data
i will implement it that way then, thanks for your advice!
write very similar functions for all vector types
Why not just use comptime to do this? You dont have to write any of this by hand
if i write something like Vector2, it will have two properties x and y, and z will be added if it was Vector3 and so on. When i have to write functions for magnitude, distance, etc, i will have to write the functions separately for Vector2 and Vector3. With a generic length instead of having x, y and z i can have a list instead whose length can be determined when i declare the variable and then i can just loop through to get each value
why not store the properties as an array? instead of accessing the 2nd element through v.y you could do v.data[1] - or similar