go - 使用反射检查结构字段类型
问题描述
我正在尝试使用 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
解决方案
推荐阅读
- android - 如何获取BLE适配器的本地名称和MAC地址?
- excel - 表格多维数据集 - Excel 过滤在节点级别不起作用
- android - 如何使用带有 LazyVerticalGrid 的 jetpack 组合分页
- graphql - 为什么仪表板中显示的动物数据库与通过 CLI 创建的不同?
- terraform - 如何在嵌套地图上按循环创建集合
- excel - 复制一系列单元格而不是整个工作表
- python - Python Openpyx 自动化引用不断变化的单元格
- python - 如何从网站获取产品详细信息的 json 数据?
- python - 如何在 Python 中将 DNA 序列列表转录为 RNA
- python - ModuleNotFoundError:VSCode 中没有名为“seaborn”的模块