在Go中将地图添加到地图中

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

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)
}

huangapple
  • 本文由 发表于 2012年9月20日 13:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/12506685.html
匿名

发表评论

匿名网友

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

确定