#how to check if anytype matches conditions

1 messages · Page 1 of 1 (latest)

gusty wharf
#

I have a generic function that can take heterogeneous struct types, but they all have to match certain conditions

  1. How can I check if the data passed to the function is correct?
  2. Also, is there a way to check at comptime, instead of runtime?
quaint iron
#

You can get the typeinfo at comptime with @typeInfo(@TypeOf(arg)), where arg is an anytype arg

gusty wharf
#

what would I do to stop compilation in case it doesn't match?

queen nacelle
#

You can use a combination of @typeInfo, @hasDecl, and @hasField. Or you can just use it as given and let the compiler error if there's something missing

#

There's @compileError

gusty wharf
queen nacelle
#

Well, yeah. If a function takes anytype and tries to use the method foo, but a type without foo is passed, then the compiler has to error