Arrays 如何在golang中动态设置运行时数组的索引?
我找了很多,但找不到合适的解决办法。我试图使用golang中的数组和切片创建以下内容作为最终输出Arrays 如何在golang中动态设置运行时数组的索引?,arrays,go,slice,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 Indust
[
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_id作为值
谁能告诉我如何做到这一点
谢谢
编辑
我的意思是我需要像这样的输出
[
11 => [1,2,3],
12 => [4,5],
]
其中,
11
和12
是json中给出的行业id,用作数组的键,[1,2,3]
,[4,5]
是要设置为数组中的值的表单id 一种更有效的方法可能是编写一个定制的JSON解码函数,并将其解码到一个映射中,其中键是您的行业id
。但是,如果必须使用数组/切片,它可以是这些行上的内容(添加函数索引的第一个参数可以是您的行业id
-将mystruct
定义更改为您需要的任何内容):
主程序包
进口(
“fmt”
)
键入mystruct[]int
var ns[]mystruct
func main(){
ns=make([]mystruct,1,1)
加(1,[]整数{2222,24,34})
加(7,[]整数{5})
加(13,[]整数{4,6,75})
加(14,[]整数{8})
加(16,[]整数{1,4,44,67,77})
fmt.Println(“你好,操场”,ns)
}
func add(索引int,ms mystruct){
nscap:=上限(ns)
nslen:=len(ns)
//格式打印LN(nscap、nslen、索引、ms)
如果索引>=nscap{
//计算所需的新nslen和nscap
//这只是一个样本——加倍
newnscap:=索引*2
newnslen:=newnscap-1
nstemp:=make([]mystruct、newnslen、newnscap)
副本(nstemp,ns)
ns=nstemp
fmt.Println(“新长度和容量:”,cap(ns),len(ns))
nscap=上限(ns)
nslen=len(ns)
}
//上述容量和长度可能已更改,请检查
如果索引=nslen{
fmt.Println(“延长切片长度”,nslen,“达到容量”,nscap)
ns=ns[:nscap]
}
ns[指数]=ms
}
在操场上:我想你可能想做的是定义一个结构来描述你试图解码的JSON模型,将JSON解组到该结构的一个片段中,然后循环遍历每个解码的值,将其放在一个映射中
这方面的一个例子如下:
不超清晰,使用转换为类似数组的行业id作为键
。你能发布一个你想要的输出的例子吗?@dm03514我已经编辑了这个问题,请现在检查。谢谢你的回复,让我检查一下它是否与我的代码一起工作。
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
}