Question: in golang how to convert slice to struct

scene 1:use reflect convert slice to struct

func SliceToStruct(array interface{}) (forwardPort *ForwardPort, err error) {
	forwardPort = &ForwardPort{}
	valueOf := reflect.ValueOf(forwardPort)
	if valueOf.Kind() != reflect.Ptr {
		return nil, errors.New("must ptr")
	}
	valueOf = valueOf.Elem()
	if valueOf.Kind() != reflect.Struct {
		return nil, errors.New("must struct")
	}

	switch array.(type) {
	case []string:
		arrayImplement := array.([]string)
		for i := 0; i < valueOf.NumField(); i++ {
			if i >= len(arrayImplement) {
				break
			}
			val := arrayImplement[i]
			if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
				valueOf.Field(i).Set(reflect.ValueOf(val))
			}
		}
	case []interface{}:
		arrayImplement := array.([]interface{})
		for i := 0; i < valueOf.NumField(); i++ {
			if i >= len(arrayImplement) {
				break
			}
			val := arrayImplement[i]
			if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
				valueOf.Field(i).Set(reflect.ValueOf(val))
			}
		}
	}

	return forwardPort, nil
}

struct to anything

https://github.com/fatih/structs

相关文章:

  • 2021-07-09
  • 2021-10-01
  • 2022-12-23
  • 2021-10-29
  • 2021-09-17
  • 2021-06-22
  • 2021-08-18
猜你喜欢
  • 2021-05-20
  • 2022-12-23
  • 2021-07-05
  • 2022-12-23
  • 2021-04-10
  • 2021-06-13
  • 2021-12-05
相关资源
相似解决方案