Generics as function parameters

Hey !

Recently I’ve had to pass generics with lots of function parameters as an argument to a function.

What I’ve ended doing is :

pub fn factorization(x: anytype) Result(x) {
  const a = asMatrix(x);
  // ...
}

pub fn asMatrix(x: anytype) Matrix(x.Scalar, x.size[0], x.size[1]) {
  assert(@TypeOf(x) == Matrix(x.Scalar, x.size[0], x.size[1])
  return x;
}

But I have two issues with my solution :

  1. It seems to be non-idiomatic zig code, and I’ve studied std for a bit and the solution they seem to pass the generic’s arguments as a parameter (which is not ideal)
  2. The errors generated by it are not good (when you don’t pass a matrix type, as it seems like the result is evaluated first)

But the main advantage of using it is that I can switch on the type (like interpret the array as a matrix if the type is not one). This last advantage is what I mainly use in my code but I’ve reduced it to this case.

What are you guys thoughts ? What would you use ? What do you do in your codebases ? What is zig’s idiomatic way ?