I'm writing a tool which can help me set any field value of an object, but there's a problem.
I have two structs Player & Card:
type Player struct {
Name string
IDCard Card
}
type Card struct {
ID string
}
there is the function
func setVal(data interface{}, fieldPath []string, val string) {
// ...
}
what the function supposed to do is to set data's specific field value to val. For Example
p := Player{
Name: "Tsuru",
IDCard: Card{ID: "id"},
}
fieldPath_Name := []string{"Name"}
fieldPath_ID := []string{"IDCard", "ID"}
setVal(&p, fieldPath_Name, "Miku") // set p.Name to "Miku"
setVal(&p, fieldPath_ID, "newID") // set p.IDCard.ID to "newID"
means to set field Name to "Miku", and ID to "newID" in IDCard which is the field of object p.
My method is to recursively get the value and type of every field using golang reflect according to fieldPath.
Now the name setting can be successful, but how can I finish the ID setting? IDCard is a struct and is one of the fields of Player.
Thanks!
Aucun commentaire:
Enregistrer un commentaire