golang property := []map[string]interface{}{ {"name": "David", "age": 50}, {"name": "Eve", "age": 60}, } 利用反射 获取property中所有name 组成新的数组
可以使用反射来实现该功能,具体步骤如下:
- 定义一个空的字符串数组,用于存储所有的name值。
- 遍历property数组,获取每个元素的值。
- 利用反射获取当前元素中的name属性值,并将其添加到字符串数组中。
- 返回字符串数组作为结果。
代码实现如下:
package main
import (
"fmt"
"reflect"
)
func main() {
property := []map[string]interface{}{
{"name": "David", "age": 50},
{"name": "Eve", "age": 60},
}
var names []string
for _, p := range property {
value := reflect.ValueOf(p["name"])
if value.Kind() == reflect.String {
names = append(names, value.String())
}
}
fmt.Println(names)
}
输出结果为:[David Eve]。
原文地址: https://www.cveoy.top/t/topic/qLV 著作权归作者所有。请勿转载和采集!