jeudi 20 mai 2021

Checking Struct fields Type using reflect

I am trying to check struct fields using Go reflect package. I have tried it in many ways and found two possible ways. But in the second way i have mentioned in below, complex or custom types can not be checked (example uuid.UUID). Only types that are included in reflect.Kind. Is there any other possible way to check custom type (example uuid.UUID) using reflect ?

First Way run here

 package main
 
 import (
    "fmt"
    "reflect"
 
    "github.com/google/uuid"
 )
 
 type Object struct {
    A string
    B int64
    C uuid.UUID
    D int
 }
 
 func main()  {
    obj :=Object{}
    typ := reflect.TypeOf(obj)
    for i := 0; i < typ.NumField(); i++{
        switch {
        case typ.Field(i).Type == reflect.TypeOf(""):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(""))
 
        case typ.Field(i).Type == reflect.TypeOf(int64(0)):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(int64(0)))
 
        case typ.Field(i).Type == reflect.TypeOf(uuid.New()):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(uuid.New()))
 
        default:
            fmt.Printf("default: type of field %s is %v \n", typ.Field(i).Name, typ.Field(i).Type)
        }
    }
 }

Output:

type of field A is string 
type of field B is int64 
type of field C is uuid.UUID 
default: type of field D is int 

Second Way - replacing switch as below run here

        switch typ.Field(i).Type.Kind(){
        case reflect.String:
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.String)

        case reflect.Int64:
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.Int64)

        default:
            fmt.Printf("default: type of field %s is %v \n", typ.Field(i).Name, typ.Field(i).Type)
        }

Output:

type of field A is string 
type of field B is int64 
default: type of field C is uuid.UUID 
default: type of field D is int 




Aucun commentaire:

Enregistrer un commentaire