github.com/gogf/gf@v1.16.9/util/gutil/gutil_struct.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gutil
     8  
     9  import (
    10  	"github.com/gogf/gf/util/gconv"
    11  	"reflect"
    12  )
    13  
    14  // StructToSlice converts struct to slice of which all keys and values are its items.
    15  // Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
    16  func StructToSlice(data interface{}) []interface{} {
    17  	var (
    18  		reflectValue = reflect.ValueOf(data)
    19  		reflectKind  = reflectValue.Kind()
    20  	)
    21  	for reflectKind == reflect.Ptr {
    22  		reflectValue = reflectValue.Elem()
    23  		reflectKind = reflectValue.Kind()
    24  	}
    25  	switch reflectKind {
    26  	case reflect.Struct:
    27  		array := make([]interface{}, 0)
    28  		// Note that, it uses the gconv tag name instead of the attribute name if
    29  		// the gconv tag is fined in the struct attributes.
    30  		for k, v := range gconv.Map(reflectValue) {
    31  			array = append(array, k)
    32  			array = append(array, v)
    33  		}
    34  		return array
    35  	}
    36  	return nil
    37  }