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

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

Want to take a map to a slice structure

问题

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

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

  1. type Attribute struct {
  2. AttId container.AttrID
  3. AttMess []json.RawMessage
  4. }

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

  1. keys := make([]container.AttrID, 0, len(AttId))
  2. for k := range AttId {
  3. keys = append(keys, k)
  4. }
  5. for _, k := range keys {
  6. fmt.Println(k, AttId[k])
  7. }

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

谢谢!

英文:

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 ,

  1. type Attribute struct {
  2. AttId container.AttrID
  3. AttMess []json.RawMessage
  4. }

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

  1. keys := make([]container.AttrID, 0, len(AttId))
  2. for k := range AttId {
  3. keys = append(keys, k)
  4. }
  5. for _, k := range keys {
  6. fmt.Println(k, AttId[k])
  7. }

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类型:

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

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

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

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:

确定