I know it would not be very idiomatic but I would like to know if it is possible to get the field name of a pointer using reflection assuming it is known that the pointer references a struct field (maybe even having the struct value in question). For example
package main
import "fmt"
type Example struct {
Foo int
Bar string
}
func GetFieldName(originStruct any, fieldPtr any) string { ... }
func main() {
v := Example{ 42, "baz" }
f := &(v.Foo)
fmt.Println(GetFieldName(v, f))
// Prints "Foo"
}
A more advanced version of this would recursively get the path of the field even if along the way there are structs or slices and return a full path to the nested field pointer.
For example GetFieldPath(v, &(v.Foos[3].Bar)) -> []any{"Foos", 3, "Bar"}
or something similar.
Why would I ever need this? — I am building a small experimental frontend framework all in golang and I need this to implement double binding in a clean way (without passing strings around)
Aucun commentaire:
Enregistrer un commentaire