代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。