Suppose we have a struct that contains fields that are defined as structs also. In the example below, the Children
field of the Parent
struct is an array of pointers to the Child
struct too. How do I create a function that can take any arbitrary struct, recurse through it (flexible depth) and update all variables of a certain type (or pointer of a certain type)?
type Child struct {
Name string
Age int
Something *string
}
type Parent struct {
Name string
Surname *string
Children []*Child
PetNames []string
Parents [2]*Parent
Others []Child
Child
}
func sanitizeStringsInStruct(c interface{}, ssf func(string) string) {
v:= reflect.ValueOf(c)
val := v.Elem()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
switch field.Kind() {
case reflect.String:
str := ssf(field.Interface().(string))
field.SetString(str)
case reflect.Interface:
fmt.Println("Interface")
case reflect.Struct:
fmt.Printf("Struct: %v %v\n", val.Type().Field(i).Name, val.Type().Field(i).Type)
// Skip private fields
if !field.CanInterface() {
continue
}
// Need assistance
case reflect.Slice:
varName := val.Type().Field(i).Name
varType := val.Type().Field(i).Type
if !field.CanInterface() {
continue
}
fmt.Println("Slice", reflect.ValueOf(field.Interface()), varName, varType
case reflect.Ptr:
// Need assistance
default:
varName := val.Type().Field(i).Name
varType := val.Type().Field(i).Type
varKind := val.Field(i).Kind()
fmt.Println("Some type: \t", varName, varType, varKind)
}
}
How should I fix the code above o support recursively iterating through slices, arrays and pointers?
Thanks
Aucun commentaire:
Enregistrer un commentaire