How to dispatch based on whether a type has fields or not?

I want to dispatch based on whether the type has fields or not. I have now

hasfieldnames(::Type{T}) where T = fieldnames(T) >= 1

fn(::Type{T}) where T = begin
   if hasfieldnames(T)
      _fn_has_field_name(T)
   else
      _fn_has_no_field_name(T)
   end
end

Is this the best way? I think the if-else is redundant and potentially bad for performance and can be gotten rid of if I knew how to make fn dispatch on whether T has field names or not.

You probably meant fieldcount instead of fieldnames. You could also use

hasfieldnames(::Type{T}) where T = isconcretetype(T) && !isprimitivetype(T) && sizeof(T) > 0

which I believe is equivalent, but has the advantage that it constant-folds, so that the compiler will completely remove the unused branch in the if-else.

4 Likes