vendredi 18 décembre 2020

How to know if a struct's field is a pointer to struct or a struct or neither?

I'm using this code to scan each field of a struct.

var myModel *types.Struct
myModel, ok = pkg.Types.Scope().Lookup("customModel").Type().Underlying().(*types.Struct)
if !ok {
  panic()
}

for i := 0; i < myModel.NumFields(); i++ {
  if IsStruct(myModel.Field(i)) {
    println("How to do?")
  }
}

func IsPointer(field *types.Var) bool {
    _, ok := field.Type().Underlying().(*types.Pointer)
    return ok
  // THIS IS WORKING VERY WELL!
}

func IsStruct(*types.Var) {
  //HOW TO DO THIS?
  //I tried return reflect.TypeOf(field).Kind() == reflect.Struct but doesn't work!
}

I need to know if a field of my Struct is a Struct or not.

This field can be pointer or not.

Example:

type customModel struct {
  A string
  B *AnotherStruct
  C *AnotherOne
}

I tried return reflect.TypeOf(field).Kind() == reflect.Struct but doesn't.

IsPointer function as you can see it's working because I can use interface check.

How to do this with structs or *structs types?





Aucun commentaire:

Enregistrer un commentaire