go slice to struct

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

上一篇:011Java并发包008集合中的线程安全问题


下一篇:当参数是Object类型时,传入int类型问题分析