首页 > 解决方案 > 使用反射检查结构字段类型

问题描述

我正在尝试使用 Goreflect包检查结构字段。我尝试了很多方法,发现了两种可能的方法。但是在下面我提到的第二种方式中,无法检查复杂或自定义类型(例如 uuid.UUID)。仅包含在reflect.Kind中的类型。有没有其他可能的方法来检查自定义类型(例如 uuid.UUID)reflect

第一条路 在这里运行

 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)
        }
    }
 }

输出:

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 

第二种方式 - 更换开关如下运行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)
        }

输出:

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 

标签: gostructreflection

解决方案


推荐阅读