需求:有一个切片,其元素是不固定类型的结构体,如何转换为元素为map类型的切片。
以下例子是通过反射reflect的方法来完成这个转换过程。
package main
import (
"fmt"
"reflect"
)
type Student struct {
Name string `json:"name"`
Age uint `json:"age"`
}
type Teacher struct {
Name string `json:"name"`
Gender uint `json:"gender"`
}
// StructSliceToMapSlice : struct切片转为map切片
func StructSliceToMapSlice(source interface{}) {
// 判断,interface转为[]interface{}
v := reflect.ValueOf(source)
if v.Kind() != reflect.Slice {
panic("ERROR: Unknown type, slice expected.")
}
l := v.Len()
ret := make([]interface{}, l)
for i := 0; i < l; i++ {
ret[i] = v.Index(i).Interface()
}
// 转换之后的结果变量
res := make([]map[string]interface{}, 0)
// 通过遍历,每次迭代将struct转为map
for _, elem := range ret {
data := make(map[string]interface{})
objT := reflect.TypeOf(elem)
objV := reflect.ValueOf(elem)
for i := 0; i < objT.NumField(); i++ {
data[objT.Field(i).Name] = objV.Field(i).Interface()
}
res = append(res, data)
}
fmt.Printf("==== Convert Result ====\n%+v\n", res)
}
func main() {
var people []interface{}
// 切片添加Student元素
stu1 := Student{
Name: "Ame",
Age: 18,
}
stu2 := Student{
Name: "Maybe",
Age: 20,
}
people = append(people, stu1)
people = append(people, stu2)
// 切片添加Teacher元素
tech := Teacher{
Name: "Rotk",
Gender: 0,
}
people = append(people, tech)
StructSliceToMapSlice(people)
}
示例结果:
==== Convert Result ====
[map[Name:Ame Age:10] map[Age:20 Name:Maybe] map[Name:Rotk Gender:0]]