drmticpet66231422 2012-09-20 05:44
浏览 27
已采纳

在Go中将地图追加到地图

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?

  • 写回答

2条回答 默认 最新

  • dongyang7152 2012-09-20 12:12
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错