英文:
Appending maps to a map in Go
问题
我正在尝试构建一个类似于这样的map[string]map[string]string:
{ "notes":
{
"Title":note.Title,
"Body":note.Body,
},
{
"Title":note.Title,
"Body":note.Body,
},
{
"Title":note.Title,
"Body":note.Body,
},
}
从一个结构体(notes)的结构体(note)中。
我考虑过这样做:
for _, note := range notes {
thisNote := map[string]string{
"Title":note.Title,
"Body":note.Body,
}
content["notes"] = append(content["notes"], thisNote)
}
但显然这不会起作用,因为我试图将一个map附加到另一个map而不是一个切片。
我是否错过了一个非常简单的解决方案?
英文:
I am trying to build a map[string]map[string]string which will look something like this:
{ "notes":
{
"Title":note.Title,
"Body":note.Body,
},
{
"Title":note.Title,
"Body":note.Body,
},
{
"Title":note.Title,
"Body":note.Body,
},
}
from a struct (notes) of structs (note)
I have thought of doing it like this:
for _, note := range notes {
thisNote := map[string]string{
"Title":note.Title,
"Body":note.Body,
}
content["notes"] = append(content["notes"], thisNote)
}
But obviously that is not going to work because I am trying to append a map to a map rather than a slice.
Is there a really easy solution to this that I am missing?
答案1
得分: 3
感谢Running Wild提供的答案,这是在评论中提到的,但我想在这里添加给任何试图做相同事情的人。
问题是我需要创建一个map[string][]map[string]string
而不是map[string]map[string]string
英文:
Thanks to Running Wild for this answer, it was in a comment but I thought I would add it here for anyone trying to do the same thing.
The issue was that I needed to make a map[string][]map[string]string
rather than a map[string]map[string]string
答案2
得分: 1
我相信你可以使用这样的结构体,因为mustache将数据作为interface{}
接收。
func handler(w http.ResponseWriter, r *http.Request) {
var data struct {
Notes []*Note
}
notes := ...
data.Notes = notes
tmpl := ...
templ.Render(data, w)
}
英文:
I'm pretty sure you can use a struct like this instead since mustache receives the data as an interface{}
func handler(w http.ResponseWriter, r *http.Request) {
var data struct {
Notes []*Note
}
notes := ...
data.Notes = notes
tmpl := ...
templ.Render(data, w)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论