如何在golang中运行时动态设置数组的索引?

时间:2017-09-21 11:19:44

标签: arrays go slice

我已经搜索了很多关于它的信息,但找不到合适的解决方案。我想要做的是使用golang中的数组和切片创建以下作为最终输出。

[
  11 => [1,2,3],
  12 => [4,5],
]

我实施的是:

type Industries struct {
    IndustryId  int         `json:"industry_id"`
    FormIds     []int       `json:"form_ids"`
}


var IndustrySettings IndustrySettings
_ := json.NewDecoder(c.Request.Body).Decode(&IndustrySettings)
var industryArr []int

for _, val := range IndustrySettings.IndustrySettings {
    industryArr = append(industryArr, val.IndustryId)   
}

在此IndustrySettings中包含以下json

{
    "industry_settings": [{
            "industry_id": 11,
            "form_ids": [1, 2, 3]
        },
        {
            "industry_id": 12,
            "form_ids": [4, 5]
        }
    ]
}

我想循环遍历这个json并转换为像industry_id这样的数组作为键,将form_ids转换为值。

有人可以告诉我们如何做到这一点吗?

谢谢!

修改

我的意思是我需要输出

[
  11 => [1,2,3],
  12 => [4,5],
]

其中1112是json中给出的industry_id,用作数组的键,[1,2,3][4,5]是要设置的表单ID作为数组中的值。

2 个答案:

答案 0 :(得分:1)

我认为您可能想要做的是定义一个描述您尝试解码的JSON模型的结构,将JSON解组为该结构的一部分,然后循环遍历每个已解码的值,将其放置在地图中。

这方面的一个例子是: https://play.golang.org/p/Dz8XBnoVos

答案 1 :(得分:0)

更有效的方法可能是编写自定义的JSON解码函数并将其解码为带有密钥industry_id的地图。但是如果你必须使用数组/切片,它可以是这些行上的东西(add函数index的第一个参数可以是你的industry_id - 更改mystruct定义到无论你需要什么):

package main

import (
    "fmt"
)

type mystruct []int

var ns []mystruct

func main() {

    ns = make([]mystruct, 1, 1)

    add(1, []int{2222, 24, 34})
    add(7, []int{5})
    add(13, []int{4,6,75})
    add(14, []int{8})
    add(16, []int{1, 4, 44, 67, 77})

    fmt.Println("Hello, playground", ns)
}

func add(index int, ms mystruct) {

    nscap := cap(ns)
    nslen := len(ns)
    //fmt.Println(nscap, nslen, index, ms)

    if index >= nscap {
        //Compute the new nslen & nscap you need
        //This is just for a sample - doubling it

        newnscap := index * 2
        newnslen := newnscap - 1

        nstemp := make([]mystruct, newnslen, newnscap)
        copy(nstemp, ns)
        ns = nstemp

        fmt.Println("New length and capacity:", cap(ns), len(ns))

        nscap = cap(ns)
        nslen = len(ns)
    }
    //Capacity and length may have changed above, check
    if index < nscap && index >= nslen {
        fmt.Println("Extending slice length",  nslen, "to capacity", nscap)
        ns = ns[:nscap]
    }
    ns[index] = ms
}

在操场上:https://play.golang.org/p/fgcaM1Okbl