Fieldnames for a user-defined struct

Suppose I have a variable ‘x’ which is of type ‘mydatatype’ which is a user-defined struct.

When I tried


I got a method error.

Is it because I need a method of ‘fieldnames’ for my self-defined datatype?

It operates on a DataType:

julia> struct X

julia> fieldnames(X) # X is a type
(:a, :b)

julia> fieldnames(X(1,2)) # X(1, 2) is an object of type X
ERROR: MethodError: no method matching fieldnames(::X)

Note that, if you have some x and aren’t sure what type to specify for it, you could also fieldnames(typeof(x)).

Side note: I wonder if this should be default behavior, e.g. fieldnames(x::T) where {???} = fieldnames(T) if it’s possible to declare that T is an instance and not a type in itself.

1 Like

It is possible to just define

fieldnames(x) = fieldnames(typeof(x))

since it will hit the most specific method that matches. Not recommending this, BTW.