doutuan8887 2016-04-28 23:08
浏览 30
已采纳

使用Go语言将地图嵌入到结构中

So in this answerhere, it's stated that one cannot embed a map into a struct in go. However, I was fiddling around with it, and came up with this and it does actually work, and is pretty straight forward.

    package main

import (
    "fmt"
    "runtime"
)

type record struct {
    m map[string]int
}




func main() {
    practice := record{m:make(map[string]int)}
    practice.m["foo"] = 2
    fmt.Println(practice.m)
    runtime.GC()
}

this prints map[foo:2]

However, my question is that, are there any negative sides to using this implementation of maps in structs, or are is there more efficient ways to do this?

  • 写回答

2条回答 默认 最新

  • dongwh1992 2016-04-28 23:23
    关注
    1. You can do that, it's absolutely fine.

    2. That isn't "embedding". Embedding means something specific — including a nameless field of a named type in a struct. Your map isn't embedded, it's a regular member with the name "m".

    3. The answer that you linked is slightly misleading: the answer to the question there ("can I flatten this JSON output without a MarshalJSON method") is indeed no, but it's not actually true that embedding a map in a struct is forbidden. If you create a named type that is a map type, you can embed it in a struct just fine. It just doesn't output in JSON the way that the person asking that question would have liked.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料