improve gconv.Interfaces by adding support for type map as its parameter

This commit is contained in:
Jack
2020-12-04 14:33:47 +08:00
parent 5171250a9d
commit ce9a0555c5
2 changed files with 30 additions and 0 deletions

View File

@ -113,6 +113,13 @@ func Interfaces(i interface{}) []interface{} {
array[i] = reflectValue.Index(i).Interface()
}
// Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
case reflect.Map:
array = make([]interface{}, 0)
for _, key := range reflectValue.MapKeys() {
array = append(array, key.Interface())
array = append(array, reflectValue.MapIndex(key).Interface())
}
// Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
case reflect.Struct:
array = make([]interface{}, 0)
// Note that, it uses the gconv tag name instead of the attribute name if

View File

@ -36,6 +36,29 @@ func Test_Strings(t *testing.T) {
})
}
func Test_Slice_Interfaces(t *testing.T) {
// map
gtest.C(t, func(t *gtest.T) {
array := gconv.Interfaces(g.Map{
"id": 1,
"name": "john",
})
t.AssertIN(array, []interface{}{"id", 1, "name", "john"})
})
// struct
gtest.C(t, func(t *gtest.T) {
type A struct {
Id int `json:"id"`
Name string
}
array := gconv.Interfaces(&A{
Id: 1,
Name: "john",
})
t.AssertIN(array, []interface{}{"id", 1, "Name", "john"})
})
}
func Test_Slice_PrivateAttribute(t *testing.T) {
type User struct {
Id int `json:"id"`