How to access class or record field with the name of the field as a string?
Say you have a record or class:
record R {
var value: int;
}
How can I access the field value
by using the string "value"
?
For example, in Python, you can access fields using the getattr
built-in:
class C:
def __init__(self, val):
self.value = val
c = C(2)
print(getattr(c, 'value')) # prints 2
What would this look like in Chapel?
The Reflection
module's getField()
and getFieldRef()
routines provide this capability. For example, the following program both reads and writes the field 'value' (TIO):
use Reflection;
record R {
var value: int;
}
var myR = new R(2);
writeln(getField(myR, "value")); // print the field from 'myR' named "value"
getFieldRef(myR, "value") = 42; // get a reference to the field from 'myR' named "value" and assign to it
writeln(myR); // print the resulting record