1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
tag.go 1.11 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-06-01 20:27 . tag 移到目录下
package tag
import (
"reflect"
"strings"
)
func StructVal(s interface{}) reflect.Value {
v := reflect.ValueOf(s)
// if pointer get the underlying element≤
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
panic("not struct")
}
return v
}
func StructFields(value reflect.Value, tagName string) []reflect.StructField {
t := value.Type()
var f []reflect.StructField
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
// we can't access the value of unexported fields
if field.PkgPath != "" {
continue
}
// don't check if it's omitted
if tag := field.Tag.Get(tagName); tag == "-" {
continue
}
f = append(f, field)
}
return f
}
// Tags contains a slice of tag options
type Tags []string
// Has returns true if the given option is available in Tags
func (t Tags) Has(opt string) bool {
for i := range t {
if t[i] == opt {
return true
}
}
return false
}
func Parse(tag string) (string, Tags) {
// tag is one of followings:
// ""
// "name"
// "name,opt"
// "name,opt,opt2"
// ",opt"
res := strings.Split(tag, ",")
return res[0], res[1:]
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.22

搜索帮助

344bd9b3 5694891 D2dac590 5694891