Fieldnames for user-defined structs

julia> struct Foo
                  bar
                  baz::Int
                  qux::Float64
       end

julia> foo = Foo(1,2,3)
Foo(1, 2, 3.0)

julia> fieldnames(foo)
ERROR: MethodError: no method matching fieldnames(::Foo)

Closest candidates are:
  fieldnames(::Core.TypeofBottom)
   @ Base reflection.jl:190
  fieldnames(::Type{<:Tuple})
   @ Base reflection.jl:192
  fieldnames(::DataType)
   @ Base reflection.jl:187
  ...

Stacktrace:
 [1] top-level scope
   @ REPL[12]:1

This example is from the julia docs,
https://web.mit.edu/julia_v0.6.2/julia/share/doc/julia/html/en/manual/types.html#Composite-Types-1

It does not work as the doc states.

In my computer, the following works:

julia> fieldnames(Foo)
(:bar, :baz, :qux)

you’re reading the docs from julia version 0.6. Please use a modern version, e.g. Types · The Julia Language

2 Likes

This is the expected behavior. foo is actually an instance of the Foo struct. So, the fieldnames are attached to the struct and not to a particular instance.

1 Like

As so often, the help is your friend:

help?> fieldnames

  fieldnames(x::DataType)

  Get a tuple with the names of the fields of a DataType.

fieldnames takes a type, not an instance of a type as its argument:

julia> fieldnames(Foo)
(:bar, :baz, :qux)

julia> foo = Foo(1,2,3); fieldnames(typeof(foo))
(:bar, :baz, :qux)
1 Like

And there is propertynames for instance. It’s more useful than fieldnames which is for structure.

1 Like