#Need suggestions on how to implement multiple structs which share extremely similar functions

1 messages · Page 1 of 1 (latest)

still rover
#

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

eternal perch
#

I think that a Vector struct generic on the length is the best option

dire quiver
#

Dynamic length would probably have the least code duplication but it wouldnt be as flexible
But you probably dont need any flexibility here

still rover
dire quiver
#

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

eternal perch
still rover
still rover
dire quiver
still rover
dire quiver
still rover
# dire quiver > write very similar functions for all vector types Why not just use comptime t...

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

eternal perch