2 回答
TA贡献1813条经验 获得超2个赞
似乎您正在尝试使用 slice 访问器获取属性,这在 Go 中不起作用。您需要为每个属性编写一个函数。这是品牌的示例:
func getUniqueBrands(v []Car) []string {
var combined []string
tempMap := make(map[string]bool)
for _, c := range v {
if _, p := tempMap[c.brand]; !p {
tempMap[c.brand] = true
combined = append(combined, c.brand)
}
}
return combined
}
另外,请注意此处用于获取 Car 值的 for 循环。Gorange可用于仅遍历索引或同时遍历索引和值。通过分配给 来丢弃索引_。
我建议重新使用此代码并添加一个 switch-case 块以获得您想要的结果。如果需要返回多种类型,请使用interface{}类型断言。
TA贡献1895条经验 获得超3个赞
也许您可以将您的结构编组为 json 数据,然后将其转换为地图。示例代码:
package main
import (
"encoding/json"
"fmt"
)
type RandomStruct struct {
FieldA string
FieldB int
FieldC string
RandomFieldD bool
RandomFieldE interface{}
}
func main() {
fieldName := "FieldC"
randomStruct := RandomStruct{
FieldA: "a",
FieldB: 5,
FieldC: "c",
RandomFieldD: false,
RandomFieldE: map[string]string{"innerFieldA": "??"},
}
randomStructs := make([]RandomStruct, 0)
randomStructs = append(randomStructs, randomStruct, randomStruct, randomStruct)
res := FetchRandomFieldAndConcat(randomStructs, fieldName)
fmt.Println(res)
}
func FetchRandomFieldAndConcat(randomStructs []RandomStruct, fieldName string) []interface{} {
res := make([]interface{}, 0)
for _, randomStruct := range randomStructs {
jsonData, _ := json.Marshal(randomStruct)
jsonMap := make(map[string]interface{})
err := json.Unmarshal(jsonData, &jsonMap)
if err != nil {
fmt.Println(err)
// panic(err)
}
value, exists := jsonMap[fieldName]
if exists {
res = append(res, value)
}
}
return res
}
- 2 回答
- 0 关注
- 130 浏览
添加回答
举报
