英文:
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})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论