1 Star 1 Fork 0

vincent/gcutil

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
reflectx.go 1.93 KB
一键复制 编辑 原始数据 按行查看 历史
vincent 提交于 2023-02-16 15:22 +08:00 . feat(): respModel的整理
package reflectx
import (
"errors"
"reflect"
)
// IsPoint 判断是否为指针
func IsPoint(m interface{}) bool {
return reflect.TypeOf(m).Kind() == reflect.Ptr
}
func NilOrZero(m interface{}, fs string) bool {
if m == nil {
return true
}
//t := reflect.TypeOf(m)
//if IsPoint(m) {}
return false
}
func GetType(m interface{}) reflect.Type {
tp := reflect.TypeOf(m)
if tp.Kind() != reflect.Ptr {
return tp
} else {
return tp.Elem()
}
}
func GetFieldByName(m interface{}, n string) (reflect.StructField, error) {
t := GetType(m)
if t.Kind() != reflect.Struct {
return reflect.StructField{}, errors.New("input object is not struct")
}
if f, exist := t.FieldByName(n); exist {
return f, nil
} else {
return f, errors.New("the field is not find")
}
}
func GetAllFieldName(m interface{}) ([]string, error) {
t := GetType(m)
if t.Kind() != reflect.Struct {
return []string{}, errors.New("input object is not struct")
}
total := t.NumField()
r := make([]string, 0, total)
for i := 0; i < total; i++ {
r = append(r, t.Field(i).Name)
}
return r, nil
}
func GetFieldValueByName(m interface{}, n string) reflect.Value {
tv := reflect.ValueOf(m)
if IsPoint(m) {
tv = tv.Elem()
}
return tv.FieldByName(n)
}
func GetValueByName(m interface{}, n string) interface{} {
tv := reflect.ValueOf(m)
if IsPoint(m) {
tv = tv.Elem()
}
return tv.FieldByName(n).Interface()
}
func SetFieldValue(m interface{}, n string, v reflect.Value) error {
tv := reflect.ValueOf(m)
if IsPoint(m) {
tv = tv.Elem()
}
fv := tv.FieldByName(n)
if fv.CanSet() {
fv.Set(v)
return nil
} else {
return errors.New("can't set the field")
}
}
// 将切片转成 []interface{}
func ToInterfaceSlice(src interface{}) []interface{} {
var ret []interface{}
if reflect.TypeOf(src).Kind() == reflect.Slice {
s := reflect.ValueOf(src)
for i := 0; i < s.Len(); i++ {
so := s.Index(i)
ret = append(ret, so.Interface())
}
}
return ret
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/vincent78/gcutil.git
git@gitee.com:vincent78/gcutil.git
vincent78
gcutil
gcutil
v1.0.1

搜索帮助