-3

I am trying to append items to this struct I have:

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
}

Any idea why my struct map[string][]Pgm errors out every time I try to add something to it? Do I need to initialize []Pgm perhaps?

kozmo
  • 4,024
  • 3
  • 30
  • 48
lakeIn231
  • 1,177
  • 3
  • 14
  • 34
  • Could you post the error you are seeing? Unless you're initializing `a.Source["Primary"]` elsewhere, `a.Source["Primary"]` will be nil. – kingkupps Apr 13 '20 at 21:27
  • The line you've highlighted as an error is trying to *read* the item at index `0`, which probably doesn't exist because you haven't appended anything to the slice (which is how you'd actually *add* something to it). – Adrian Apr 13 '20 at 21:53

1 Answers1

0

There are some error in the code:

  1. Inet type is not defined
  2. AuditSource type does not contains Id used in NewAuditSource function
  3. AuditSourceDifferences function does not contains the if statement
  4. You are appending on a (probable) not existent value of the array using the index 0 and 1 in AuditSourceDifferences function
  5. You have used the same name (a) to the input value (a, b int) and the struct receiver (a *AuditSource)

Try with the following code

package yourPackage

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

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 (a *AuditSource) AuditSourceDifferences(i, j int) bool {
    if i != j {
        a.Source["Primary"] = append(a.Source["Primary"], Pgm{MulticastPort: i},Pgm{MulticastPort: j})
    }
    return true
}

alessiosavi
  • 2,753
  • 2
  • 19
  • 38