Hi,
TL;DR: I'm trying to dynamically get a value in a struct by using the field name in a variable. I can't figure out how to do it, so I assume it's not idiomatic?
field = "a"
value = my_instance_of_mystruct.get(field);
I've found the std::slice::SliceIndex but can't figure out if I can apply it without re-implementing the trait for my struct.
Background
I have a struct, like this:
MyStruct {
a: String,
b: String,
c: f64
}
(In reality it has about 10-20 fields)
And I'm trying to convert these to Neon javascript objects. So for each of the 20 fields, I need to (depending on the field type):
value = instance_of_mystruct.a;
let js_value = cx.string(value); // for strings
let result = obj.set(cx, field, js_value);
Or:
value = instance_of_mystruct.c;
let js_value = cx.number(value); // for numbers
let result = obj.set(cx, field, js_value);
So in reality I want to loop this to not repeat myself, so I've made:
let strings = vec!["a", "b"];
let floats = vec!["c"];
for field in strings {
value = instance_of_mystruct.get(field); // Won't work, get is not implemented for a struct
let js_value = cx.number(value); // for numbers
let result = obj.set(cx, field, js_value);
}
Any good way to not having to repeat myself? Otherwise the code would become:
value = instance_of_mystruct.a;
let js_value = cx.string(value); // for strings
let result = obj.set(cx, "a", js_value);
value = instance_of_mystruct.b;
let js_value = cx.string(value); // for strings
let result = obj.set(cx, "b", js_value);
value = instance_of_mystruct.c;
let js_value = cx.number(value); // for numbers
let result = obj.set(cx, "c", js_value);
[repeat 10-20 times more, since I have a lot of fields]