How to inspect the attributes of a Struct/Mutable Struct in Julia

Viewed 664

I have a struct defined as follows:

julia> struct test
           test1::Int64
           test2::Float64
       end

I want to be able to see the names of the attributes in the struct as well as the type. What is the most straight forward way to do this? I know I can do:

julia> t = test(1,1.0)
test(1, 1.0)

julia> fieldnames(typeof(t))
(:test1, :test2)

but I would like to see the attribute name and type together.

2 Answers

Use fieldtypes(typeof(t))

julia> DataFrame(name=[fieldnames(typeof(t))...], type=[fieldtypes(typeof(t))...])
2×2 DataFrame
│ Row │ name   │ type     │
│     │ Symbol │ DataType │
├─────┼────────┼──────────┤
│ 1   │ test1  │ Int64    │
│ 2   │ test2  │ Float64  │

Regarding the other answer note that dump outputs always the entire data structure which is not good for fields having complex types. Try doing dump on a struct that has a Dict field to find out my point (or just try in the console) dump(Dict()).

The most straight forward way to do this would be to use the dump method:

help?> dump search: dump

dump(x; maxdepth=8)

Show every part of the representation of a value. The depth of the output is truncated at maxdepth.

So in this case, it would show:

julia> dump(t)
test
  test1: Int64 1
  test2: Float64 1.0

See here for more details: https://docs.julialang.org/en/v1/base/io-network/#Base.dump

Related