Golang assignment to entry in nil map

Golang assignment to entry in nil map

Golang assignment to entry in nil map

Kenapa code ini error ? atau lebih tepatnya panic kalo di Go

package main

import "fmt"

func main() {

    var m map[string]int

    m["a"] = 1

    fmt.Println(m["a"])
}

Enter fullscreen mode Exit fullscreen mode

panic: assignment to entry in nil map

solusi mengatasi panic diatas adalah menggunakan function make untuk initialize map.

package main

import "fmt"

func main() {

    var m = make(map[string]int)

    m["a"] = 1

    fmt.Println(m["a"])
}

Enter fullscreen mode Exit fullscreen mode

ketika kita deklarasi suatu map seperti ini di Go.

var m map[string]int

Enter fullscreen mode Exit fullscreen mode

kita membuat nil map. nil map sama seperti empty map panjang elemennya 0 dengan pengecualian kita tidak bisa menambah elemen di nil map.

var a map[string]int
var b = make(map[string]int)

assert.Equal(t, len(a), len(b))

Enter fullscreen mode Exit fullscreen mode

Referensi:

  • https://yourbasic.org/golang/gotcha-assignment-entry-nil-map/
  • https://yourbasic.org/golang/maps-explained/

Credit:

  • Cover photo Photo by Usman Yousaf on Unsplash

Ask a question ?

  1. Home
  2. Community
  3. GoLang
  4. Assignment To Entry In Nil Map

Why we get this error: "assignment to entry in nil map" in Go

Answers

This error occurs when you try to add elements in an empty or nil map. Before adding the elements, we have to initialize the map through the "make" function.

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos

Copyright © 2013 - 2022 MindMajix Technologies

  1. Go : assignment to entry in nil map

Solution 1

The Go Programming Language Specification

Map types

A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

make(map[string]int)
make(map[string]int, 100)

The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

You write:

var countedData map[string][]ChartElement

Instead, to initialize the map, write,

countedData := make(map[string][]ChartElement)

Solution 2

Another option is to use a composite literal:

countedData := map[string][]ChartElement{}

https://golang.org/ref/spec#Composite_literals

Comments

  • When trying to set value to the map(countedData) in the below code, I am getting an error that says, assignment to entry in nil map.

    func receiveWork(out <-chan Work) map[string][]ChartElement {
    
        var countedData map[string][]ChartElement
    
        for el := range out {
            countedData[el.Name] = el.Data
        }
        fmt.Println("This is never executed !!!")
    
        return countedData
    }
    

    Println does not execute (as the error occurs on a lien before that).

    There are some goroutines , that are sending data to channel, and receiveWork method should be making a map like this:

    map =>
        "typeOne" => 
           [
             ChartElement,
             ChartElement,
             ChartElement,
           ],
        "typeTwo" => 
           [
             ChartElement,
             ChartElement,
             ChartElement,
           ]
    

    Please help me fix the error.

Recents

Can a map be nil Golang?

The zero value of a map is nil . A nil map has no keys, nor can keys be added.

How do I iterate over a map in Golang?

As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order..
Create a slice..
Store keys to the slice..
Sort the slice by keys..
Iterate over the map by the sorted slice..

How do I initialize a map in Golang?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

How do you create an empty map in Golang?

To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.