golang 使用反射实现获取struct的field内容

本文介绍如何在Golang中利用反射(reflection)API来获取struct的field内容,包括直接使用和继承场景的应用,同时提供了constant.go、baseModel.go、exampleModel.go和excampleTest.go等代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

structReflect.go

package utils

import (
	"reflect"
	"regexp"
)

// GetStructTagName 获取struct的field的tag内容
func GetStructTagName(i interface{}, fieldName string) []string {
	types := reflect.TypeOf(i)
	numField := types.Elem().NumField()
	var tagValues = make([]string, numField)
	for i := 0; i < numField; i++ {
		tagValue := types.Elem().Field(i).Tag.Get(fieldName)
		if tagValue == "" {
			continue
		}
		tagValues[i] = tagValue
	}
	return tagValues
}

// GetStructTagNameRegex 获取struct的field的tag内容,并使用regexp
func GetStructTagNameRegex(i interface{}, fieldName string, regStr string) []string {
	reg := regexp.MustCompile(regStr)
	types := reflect.TypeOf(i)
	numField := types.Elem().NumField()
	var tagValues = make([]string, numField)
	for i := 0; i < numField; i++ {
		tagValue := types.Elem().Field(i).Tag.Get(fieldName)
		if tagValue == "" {
			continue
		}
		matchArr := reg.FindStringSubmatch(tagValue)
		tagValues[i] = matchArr[len(matchArr)-1]
	}
	return tagValues
}

直接使用如下: 

s := S{}

//获取JSON字段的内容
GetStructTagName(&s,"json")

//获取gorm字段的内容
GetStructTagNameRegex(&s,"gorm",`comment:'(.*?)'`)

 


继承使用如下:

constant.go

package utils

const (
	REGEX_COMMENT_VALUE = `comment:'(.*?)'`
	FIELD_JSON_VALUE    = "json"
    FIELD_GORM_VALUE    = "gorm"
)

baseModel.go

package model

import (
	"utils"
)

type IBaseModel interface {
	GetJsonName()     []string
	GetCommentName()  []string
}

type BaseModel struct {
	I interface{}
}

// GetJsonName 获取struct的数据库中的名称JsonName
func (b BaseModel) GetJsonName()    []string {
	return utils.GetStructTagName(b.I, utils.FIELD_JSON_VALUE)
}

// GetCommentName 获取struct的中文名称CommentName
func (b BaseModel) GetCommentName() []string {
	return utils.GetStructTagNameRegex(b.I, utils.FIELD_GORM_VALUE, utils.REGEX_COMMENT_VALUE)
}

 exampleModel.go

package model

import (
	"model"
)

type ExampleModel struct {
	Model     model.BaseModel
	Code      string  `json:"code" gorm:"primaryKey;type:varchar(10);comment:'代码'"`
	Date      string  `json:"date" gorm:"type:varchar(8);comment:'日期'"`
}

func NewExampleModel() *ExampleModel {
	return &ExampleModel{Model: model.BaseModel{I: &ExampleModel{}}}
}

excampleTest.go

package test

import (
	"fmt"
	"model"
	"testing"
)

func TestModel(t *testing.T) {
	excample :=model.NewExcampleModel()
	jsonName := excample.Model.GetJsonName()
    commentName := excample.Model.GetCommentName()
	fmt.Println(jsonName,commentName)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值