How to get Julia object fields

Given a complex Julia object, how do I define its fields?

I know one solution if you work in REPL: first you determine the type of an object by calling typeof , then enter the help mode ( ? ), And then look at the type. Is there a more programmatic way to achieve the same thing?

+5
source share
2 answers

Use fieldnames(x) , where x is either an instance of a complex type that interests you, or a DataType . That is, fieldnames(today()) and fieldnames(Date) will have the same output. This returns a Vector{Symbol} list of field names in order.

To get values ​​in any of these fields, use either getfield(x, field_name_here) or the syntax of the x.field_name_here shortcut.

Another useful and related function to play with is dump(x) .

I'm sure I saw another question, which is a pretty close duplicate of this in StackOverflow, but a quick search showed nothing. If anyone knows this, add it in the comments.

+10
source

suppose the object is obj ,

You can get all the information about your fields with the 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 field type vector.

+1
source

Source: https://habr.com/ru/post/1262904/


All Articles