If I have a struct with a fieldname 'fieldname', is it possible to access the data in that field using only the variable?
ie.
x = 'fieldname'
is it possible to do
data = struct.(x) in some way? I want to use the string in x as the field name.
Yes, this is possible using the TAG_NAMES
function:
tnames=TAG_NAMES(struct)
tindex=WHERE(STRCMP(tnames,'fieldname') EQ 1)
data=struct.(tindex)
The call to TAG_NAMES
returns an array of strings representing the tags defined in struct
.
The WHERE
statement returns the index in tnames
of a string matching 'fieldname'
.
Finally, the index is passed to the struct.(tindex)
operation, which extracts a field by
its numeric tag index.
Of course, in a real application you'd want to check whether tindex
was successfully
matched to something, otherwise IDL will choke on the structure lookup with an index
of -1.
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