Skip to content

Reflection - Set value in struct ? #4122

Answered by Kelimion
RoboMage asked this question in Q&A
Discussion options

You must be logged in to vote

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 my_struct, not &my_struct, to struct_field_value_by_name. The any parameter automatically takes the address of the thing you pass into it. So now we're passing a type Foo 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, …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@Kelimion
Comment options

@RoboMage
Comment options

Answer selected by Kelimion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants