想要将地图转换为切片结构。

huangapple go评论83阅读模式
英文:

Want to take a map to a slice structure

问题

我有一个带有键和值结构的地图,我想将其放入一个简单的切片中。

我想要将值存储为以下结构的结构体,

type Attribute struct {
    AttId      container.AttrID
    AttMess []json.RawMessage
}

我目前的循环大致如下,它从现有地图中获取键,

keys := make([]container.AttrID, 0, len(AttId))
for k := range AttId {
    keys = append(keys, k)
}

for _, k := range keys {
    fmt.Println(k, AttId[k])
}

如何构建一个包含键和值的切片,其中键和值都在上述结构体的属性中?如果您能帮忙解决这个问题,我会很感激。

谢谢!

英文:

I have a map with a key and a value structure that i want to put into a simple slice.

The struct I want to store the values as ,

type Attribute struct {
    AttId      container.AttrID
    AttMess []json.RawMessage
}

The current loop I have is something like this which takes the keys from the existing map,

	keys := make([]container.AttrID, 0, len(AttId))
	for k := range AttId {
		keys = append(keys, k)
	}

	for _, k := range keys {
		fmt.Println(k, AttId[k])
	}

How would I construct a slice that holds the keys and values inside attributes with the struct above? I'm a bit lost if you can actually make this.

Thanks!

答案1

得分: 2

你应该简单地遍历地图并构造结构的实例。假设地图的值是[]json.RawMessage类型:

attrs := make([]Attribute, 0, len(attributes))
for k, v := range attributes {
   attrs = append(attrs, Attribute{AttributesId: k, AttributesMessage: v})
}
英文:

You should simply range over the map and construct instances of the struct. Assuming the map values are []json.RawMessage types:

attrs:=make([]Attribute,0,len(attributes))
for k,v:=range attributes {
   attrs=append(attrs,Attribute{AttributesId:k, AttributesMessage:v})
}

huangapple
  • 本文由 发表于 2021年8月4日 08:15:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/68644061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定