2025-03-14 12:41:11 +08:00

30 lines
449 B
Go

package utils
import (
"fmt"
"reflect"
)
func StructToMap(s any) (map[string]any, error) {
result := make(map[string]any)
val := reflect.ValueOf(s)
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("provided value is not struct")
}
for i := range val.NumField() {
field := val.Type().Field(i)
value := val.Field(i)
if !value.IsValid() {
continue
}
result[field.Name] = value.Interface()
}
return result, nil
}