mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 08:32:40 +08:00
结构体转map
This commit is contained in:
35
structs/struct_to_map.go
Normal file
35
structs/struct_to_map.go
Normal file
@ -0,0 +1,35 @@
|
||||
package structs
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
const tagName = "json"
|
||||
|
||||
func ToMap(o any, opts ...optionFunc) map[string]any {
|
||||
typ := reflect.TypeOf(o)
|
||||
|
||||
kind := typ.Kind()
|
||||
if kind == reflect.Map {
|
||||
if h, ok := o.(map[string]any); ok {
|
||||
return h
|
||||
}
|
||||
}
|
||||
|
||||
opt := createOptions(opts)
|
||||
val := reflect.ValueOf(o)
|
||||
m := make(map[string]any)
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
fi := typ.Field(i)
|
||||
|
||||
field := getFieldOption(fi)
|
||||
source := val.FieldByName(fi.Name)
|
||||
if shouldIgnore(source, opt.IgnoreEmpty || field.omitEmpty && opt.Omitempty) {
|
||||
continue
|
||||
}
|
||||
|
||||
m[field.name] = source.Interface()
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
Reference in New Issue
Block a user