亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用“動態”鍵從地圖中提取值

使用“動態”鍵從地圖中提取值

Go
MMMHUHU 2022-12-19 19:57:04
來自javascript背景,剛開始接觸Golang。我正在學習 Golang 中的所有新術語,并創建新問題,因為我找不到我需要的答案(可能是由于缺乏要搜索的術語知識)我創建了一個自定義類型,創建了一個類型數組,我想創建一個函數,我可以在其中檢索特定鍵的所有值,并返回所有值的數組(本例中為品牌)type Car struct {  brand string  units int}....var cars []Carvar singleCar Car//So i have a loop here and inside the for-loop, i create many single carssingleCar = Car {   brand: "Mercedes",   units: 20}//and i append the singleCar into carscars = append(cars, singleCar)現在我想做的是創建一個可以檢索所有品牌的函數,我嘗試執行以下操作。我打算擁有key一個動態值,這樣我就可以通過特定的鍵進行搜索,例如品牌、型號、容量等。func getUniqueByKey(v []Car, key string) []string {    var combined []string    for i := range v {        combined = append(combined, v[i][key])         //this line returns error -        //invalid operation: cannot index v[i] (map index expression of type Car)compilerNonIndexableOperand    }    return combined    //This is suppose to return ["Mercedes", "Honda", "Ferrari"]}如果我getUniqueByKey(cars, "brand")在這個例子中使用 where,上面的函數應該可以工作,品牌是key. 但我不知道語法所以它返回錯誤。
查看完整描述

2 回答

?
慕姐8265434

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{}類型斷言。




查看完整回答
反對 回復 2022-12-19
?
蠱毒傳說

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

}


查看完整回答
反對 回復 2022-12-19
  • 2 回答
  • 0 關注
  • 91 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號