I'm trying to write a function on a struct that takes a parameter and returns the value of the field that the parameter points to. I then have several child structs that inherit from the root struct (the one with the function). When calling the method on one of those child structs to get a property that only that struct has, it throws the error panic: reflect: call of reflect.Value.Interface on zero Value
. I have created a minimal reproduction here. Is there any way for me to only have the method on the root struct while still being able to get values from a child struct?
Code (same as playground):
package main
import (
"fmt"
"reflect"
)
type Parent struct {
}
func (p Parent) Get(name string) any {
v := reflect.ValueOf(p)
return v.FieldByName(name).Interface()
}
type Child struct {
Parent
Field string
}
func main() {
child := Child{
Field: "Hello",
}
fmt.Println(child.Get("Field"))
}
Aucun commentaire:
Enregistrer un commentaire