登录
首页 >  Golang >  Go问答

无键数组/关联数组

来源:stackoverflow

时间:2024-03-04 23:36:26 425浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《无键数组/关联数组》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

欢迎大家。 告诉我如何在 go 中获得平面数组。 也就是说,有条件地,我有一个没有以下形式的键的结构:

type dashboardheatmapstruct struct {
    float64
    string
}

接下来,我以 json 的形式给出它的剩余响应,并获取以下形式的输出:

[[0,"#AEAEAE"],[0.01,"#0e00ff"],[0.65,"#00ffcf"],[0.7,"#00ffcf"],[0.75,"#00ff9c"],[0.8,"#00ff0a"],[0.85,"#b3ff00"],[0.9,"#ffdc00"],[0.95,"#ff6d00"],[1,"#c60000"]]

解决方案


声明一个结构类型来表示 json 数组的元素。

type dashboardheatmapstruct struct {
    t float64
    c string
}

在该类型上实现 json.Unmarshaler 接口:

func (d *dashboardheatmapstruct) unmarshaljson(p []byte) error {
    // p is expected to be json array with float and 
    // string values. create slice to match.
    v := []interface{}{&d.t, &d.c}

    // unmarshal to json array to the slice. the json decoder
    // follows the pointers in the slice to set the struct members.
    return json.unmarshal(p, &v)
}

实现 json.Marshler 接口以编码回 json。

func (d dashboardheatmapstruct) marshaljson() ([]byte, error) {
    v := []interface{}{d.t, d.c}
    return json.marshal(v)
}

解组为 dashboardheatmapstruct 的切片:

var result []DashboardHeatMapStruct
if err := json.Unmarshal(data, &result); err != nil {
    // handle error
}

Run it on the playground

理论要掌握,实操不能落!以上关于《无键数组/关联数组》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>