-
Hi I'm having trouble using reflection to set values in a struct. Extracting data was straightforward, but setting it using reflected data seems trickier I was under the impression struct_field_by_name was providing a pointer, but when I set the value, it doesn't set it in the struct
Does it just copy the value? Should I be using the offset in Struct_Field instead? (or struct_field_offsets) Update: I'm currently setting values like so
I obviously cut out most of my code, but is there a more concise way of doing this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi, yes. You were very close. package main
import "core:fmt"
import "core:reflect"
main :: proc() {
Foo :: struct {
a: int, b: int,
}
my_struct := Foo{a = 1, b = 2}
f := reflect.struct_field_value_by_name(my_struct, "b")
(^int)(f.data)^ = 6
fmt.println(f) // prints '6'
fmt.println(my_struct.b) // prints '6'
} Note that we're passing Similarly, the procedure itself returns an What we do here is poke into the |
Beta Was this translation helpful? Give feedback.
Hi, yes. You were very close.
Note that we're passing
my_struct
, not&my_struct
, tostruct_field_value_by_name
. Theany
parameter automatically takes the address of the thing you pass into it. So now we're passing a typeFoo
instead of type^Foo
.Similarly, the procedure itself returns an
any
, which can have any value and type assigned to it. When you performed the direct assignment of 6, …