2

I am new to golang and I am trying to create a map of type map[string]interface{}.

But when I try to create a new key when it doesn't exists, I get a runtime error "panic: assignment to entry in nil map". Can anyone tell me what I am doing wrong please?

Go PlayGround: https://play.golang.org/p/vIEE0T11yl

Here is my code:

package main

func main() {
    buffer := Buffer{}
    buffer.AddRecord("myKey", 12345)
}

type Buffer struct {
    records    map[string][]interface{}
}

// ProcessRecord adds a message to the buffer.
func (buffer *Buffer) AddRecord(key string, record interface{}) {
    _, ok := buffer.records[key]
    if !ok {
        buffer.records[key] = make([]interface{}, 0)
    }

    buffer.records[key] = append(buffer.records[key], record)
}
bn00d
  • 1,126
  • 3
  • 15
  • 21
  • I didn't knew if I was missing an initialization when I asked this question, so I don't know if this is technically a duplication. Otherwise, i knew how to initialize a map within struct or in this case map of interface slice. – bn00d Sep 18 '15 at 15:24

1 Answers1

11

You need to initialise the map itself: https://play.golang.org/p/wl4mMGjmRP

func (buffer *Buffer) AddRecord(key string, record interface{}) {
    // Check for nil, else initialise the map
    if buffer.records == nil {
        buffer.records = make(map[string][]interface{})
    }
    _, ok := buffer.records[key]
    if !ok {
        buffer.records[key] = make([]interface{}, 0)
    }

    buffer.records[key] = append(buffer.records[key], record)
}

You could also use a constructor for your struct type - e.g. NewBuffer(...) *Buffer - that initialises the field as well, but it's good practice to check for nil before using it. Same goes for accessing map keys.

elithrar
  • 23,364
  • 10
  • 85
  • 104
  • I knew I was doing something really silly mistake. Thanks a lot, you saved me lot of time – bn00d Sep 18 '15 at 05:15