How to get fields of a Julia object

2019-04-24 05:57发布

问题:

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?

回答1:

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.



回答2:

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.