"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go Basics: Why nil Slices accept new values, but nil Maps don&#t

Go Basics: Why nil Slices accept new values, but nil Maps don&#t

Published on 2024-11-01
Browse:398

New values can be added to Nil Slice but adding new values to Nil Map throws a runtime error. Let's see why

var slice []int // nil slice
slice = append(slice, 1) // append works as expected
fmt.Println(slice) // [1]

var m map[string]int // nil map
m["one"] = 1 // ? Runtime panic: assignment to entry in nil map

Why appending to a Nil Slice works:
Slice is a reference to an underlying array and dynamically-sized data structure. It consists of 3 components

  • Pointer to underlying array
  • Length of slice
  • Capacity of slice

When we declare a nil slice, the length and capacity will be zero and it doesn't point to any underlying array. Basically append operation checks the capacity and if it's not sufficient then it allocates new underlying array with enough capacity to store the new elements and returns a new slice that points to newly created array. So append works as expected.

Why adding to a Nil Map doesn't work:
Map in golang basically acts as a hash table and the internal data structures needs to be initialized first before we can store the key-value pair.

When we declare a map as nil (var m map[string]int), it is uninitialized and not yet ready to store key-value pairs. So this will create a runtime error when we try to add values to a nil map. To avoid such errors create map using make

var m map[string]int // nil map

m = make(map[string]int) // initialize it
m["one"] = 1 // map is now initialized, so we can add values
print(m) // map[one:1]

  • Does Go supports Pass By Ref ?
  • new vs make in Go
  • Does Go supports Inheritance ?
  • How to create a simple web server in Go ?

To learn more about such topics along with code examples, feel free to checkout my Github repo:

Go Basics: Why nil Slices accept new values, but nil Maps don Sai7xp / learn-golang

GoLang Basics to Advanced. Including Design Patterns, SOLID Principles & more

Release Statement This article is reproduced at: https://dev.to/sai7xp/go-basics-why-nil-slices-accept-new-values-but-nil-maps-dont-23l0?1 If there is any infringement, please contact study_golang@163 .comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3