From 9149dc140f52ac342e9ceac9aed1af34fed98d62 Mon Sep 17 00:00:00 2001 From: what-00 Date: Thu, 13 Apr 2023 10:14:55 +0800 Subject: [PATCH] =?UTF-8?q?[feat]=20=E6=96=B0=E5=A2=9E=20=E8=BE=85?= =?UTF-8?q?=E5=8A=A9=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- support/util.go | 100 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/support/util.go b/support/util.go index f89a52c..c96f4b5 100644 --- a/support/util.go +++ b/support/util.go @@ -1 +1,99 @@ -package support \ No newline at end of file +package support + +import ( + "fmt" + "reflect" + "strings" + "unsafe" +) + +func GetFieldValue(i any, k string) any { + v := reflect.ValueOf(i) + + var kv reflect.Value + + if v.Kind() == reflect.Ptr { + v = reflect.Indirect(v) + } + + if v.Kind() == reflect.Struct { + kv = v.FieldByName(k) + } else if v.Kind() == reflect.Map { + for _, key := range v.MapKeys() { + if key.String() == k { + kv = v.MapIndex(key) + } + } + } + + switch kv.Kind() { + case reflect.String: + return kv.String() + case reflect.Bool: + return kv.Bool() + case reflect.Float32, reflect.Float64: + return kv.Float() + case reflect.Int, reflect.Int64: + return int(kv.Int()) + case reflect.Invalid: + return nil + } + + return kv.Interface() +} + +func InterfaceToSlice(i any) (ret []any) { + rv := reflect.ValueOf(i) + + if rv.Kind() == reflect.Ptr { + rv = reflect.Indirect(rv) + } + + if rv.Kind() != reflect.Slice { + panic("请传入切片类型数据") + } + + for i := 0; i < rv.Len(); i++ { + ret = append(ret, rv.Index(i).Interface()) + } + + return ret +} + +func SliceConvert(origSlice any, newSliceType reflect.Type) any { + sv := reflect.ValueOf(origSlice) + + if sv.Kind() != reflect.Slice { + panic(fmt.Sprintf("无效切片类型 %T (来源)", origSlice)) + } + + if newSliceType.Kind() != reflect.Slice { + panic(fmt.Sprintf("无效切片类型 %T (目标)", newSliceType)) + } + + // 生成新类型的切片 + newSlice := reflect.New(newSliceType) + + // hdr指向到新生成切片的SliceHeader + hdr := (*reflect.SliceHeader)(unsafe.Pointer(newSlice.Pointer())) + + var newElemSize = int(sv.Type().Elem().Size()) / int(newSliceType.Elem().Size()) + + // 设置SliceHeader的Cap,Len,以及数组的ptr + hdr.Cap = sv.Cap() * newElemSize + hdr.Len = sv.Len() * newElemSize + hdr.Data = uintptr(sv.Pointer()) + + return newSlice.Elem().Interface() +} + +func UcFirst(s string) string { + if s == "" { + return "" + } + return strings.ToUpper(s[:1]) + s[1:] +} + +func StudlyCase(s string) string { + return strings.Replace(strings.Title(strings.Replace(s, "-", " ", -1)), " ", "", -1) +}