为了账号安全,请及时绑定邮箱和手机立即绑定

使用“动态”键从地图中提取值

使用“动态”键从地图中提取值

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 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号