golang工具篇-结构体合并切片

主要应用场景:
将多个结构根据字段或Tag名称导出合并到 目的结构体切片中,并可以根据MERGE_MODEL类型选择不同的导出合并模式。

package util
import (
   "fmt"
   "reflect"
   "strings"
)
type MERGE_MODEL string
const (
   FIELDMODEL      MERGE_MODEL = "FIELDMODEL"      //字段名
   TAGMODEL        MERGE_MODEL = "TAGMODEL"        //匹配标签名
   TAGORFIELDMODEL MERGE_MODEL = "TAGORFIELDMODEL" //优先匹配Tag
)
type StructUtil struct {
   
   tolerate   bool
   mergeModel MERGE_MODEL
}
type Options struct {
   
   tolerate   bool
   mergeModel MERGE_MODEL
}
type OptionFunc func(*Options)
func WithMergeModel(mergeModel MERGE_MODEL) OptionFunc {
   
   return func(o *Options) {
   
      o.mergeModel = mergeModel
   }
}
func WithTolerate(tolerate bool) OptionFunc {
   
   return func(o *Options) {
   
      o.tolerate = tolerate
   }
}
func NewStructUtil(handlers ...OptionFunc) *StructUtil {
   
   options := &Options{
   
      tolerate:   true,
      mergeModel: FIELDMODEL,
   }
   for _, o := range handlers {
   
      o(options)
   }
   return &StructUtil{
   
      tolerate:   options.tolerate,
      mergeModel: options.mergeModel,
   }
}
func MultiStructMergeToSlice[T any](util *StructUtil, data ...interface{
   }) (res []T, err error) {
   
   res = make([]T, 0, len(data))
   for index, val := range data {
   
      rfv := reflect.ValueOf(val)
      if !rfv.IsValid() && !util.tolerate 

你可能感兴趣的:(golang)