Given a Julia object of composite type, how can one determine its fields?
I know one solution if you're working in the REPL: First you figure out the type of the object via a call to typeof
, then enter help mode (?
), and then look up the type. Is there a more programmatic way to achieve the same thing?
For v0.7+
Use fieldnames(x)
, where x
is a DataType
. For example, use fieldnames(Date)
, instead of fieldnames(today())
, or else use fieldnames(typeof(today()))
.
This returns Vector{Symbol}
listing the field names in order.
If a field name is myfield
, then to retrieve the values in that field use either getfield(x, :myfield)
, or the shortcut syntax x.myfield
.
Another useful and related function to play around with is dump(x)
.
Before v0.7
Use fieldnames(x)
, where x
is either an instance of the composite type you are interested in, or else a DataType
. That is, fieldnames(today())
and fieldnames(Date)
are equally valid and have the same output.
suppose the object is obj
,
you can get all the information of its fields with following code snippet:
T = typeof(obj)
for (name, typ) in zip(fieldnames(T), T.types)
println("type of the fieldname $name is $typ")
end
Here, fieldnames(T)
returns the vector of field names and T.types
returns the corresponding vector of type of the fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With