Go 如何将项目附加到映射[string][]结构

Go 如何将项目附加到映射[string][]结构,go,go-map,Go,Go Map,我正在尝试将项附加到此结构中我有: type AuditSource struct { Source map[string][]Pgm `json:"Source"` } type Pgm struct { ID uint `json:"id,omitempty"` SourceIP Inet `json:"sourceip,omitempty"` MulticastPort int `json:"multic

我正在尝试将项附加到此结构中我有:

type AuditSource struct {
    Source      map[string][]Pgm  `json:"Source"`
}

type Pgm struct {
    ID            uint   `json:"id,omitempty"`
    SourceIP      Inet   `json:"sourceip,omitempty"`
    MulticastPort int `json:"multicastport,omitempty"`
}


func NewAuditSource(lid string) (a *AuditSource) {
    a = &AuditSource{
        Id:              make(map[string]uint64),
        Source:          make(map[string][]Pgm),
    }
    return
}

func (as *AuditSource) AuditSourceDifferences(a, b int) bool{

        if a != b {
            as.Source["Primary"][0].MulticastPort =a //ERRORS out every time
            as.Source["Primary"][1].MulticastPort =b 

        }
       return true
}

你知道为什么每次我尝试添加东西时,我的结构映射[string][]Pgm都会出错吗?我是否需要初始化[]Pgm?

您似乎已经初始化了映射,因此错误很可能是因为您正在访问切片中不存在的元素。初始化切片时,切片为空,不存在第0个或第1个元素:

src:=a.Source["Primary"]
src=append(src,Pgm{MulticastPort:a})
src=append(src,Pgm{MulticastPort:b})
a.Source["Primary"]=src

代码中有一些错误:

  • Inet
    未定义类型
  • AuditSource
    类型不包含在
    NewAuditSource
    函数中使用的
    Id
  • AuditSourceDifferences
    函数不包含
    if
    语句
  • 您正在使用
    AuditSourceDifferences
    函数中的索引0和1追加(可能)不存在的数组值
  • 您对输入值(
    a,b int
    )和结构接收器(
    a*AuditSource)使用了相同的名称(
    a
  • 请尝试使用以下代码

    打包您的包
    类型AuditSource结构{
    源映射[string][]Pgm`json:“源”`
    Id映射[字符串]uint64
    }
    类型Pgm结构{
    ID uint`json:“ID,empty”`
    SourceIP Inet`json:“SourceIP,省略empty”`
    MulticastPort int`json:“MulticastPort,省略空”`
    }
    func NewAuditSource(lid字符串)(a*AuditSource){
    a=&AuditSource{
    Id:make(映射[字符串]uint64),
    来源:make(映射[字符串][]Pgm),
    }
    回来
    }
    func(a*AuditSource)AuditSourceDifferences(i,j int)bool{
    如果我!=j{
    a、 Source[“Primary”]=append(a.Source[“Primary”],Pgm{multiccastport:i},Pgm{multiccastport:j})
    }
    返回真值
    }
    
    您能发布您看到的错误吗?除非在别处初始化
    a.Source[“Primary”]
    ,否则
    a.Source[“Primary”]
    将为零。您突出显示为错误的行是尝试读取索引
    0
    处的项,该项可能不存在,因为您没有向切片添加任何内容(实际上就是这样添加内容的)。这似乎是不必要的冗长,因为您可以附加到
    nil
    切片
    a.Source[“Primary”]=append(a.Source[“Primary”],Pgm{multiccastport:a})
    可以正常工作。