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 關注
- 91 瀏覽
添加回答
舉報