Development notes

Thoughts, notes and ideas about development

Go Slices and Maps

This post describes some slice and maps features which may be opaue.


A slice is like a arrays but with variadic lenght. A slice has both a length and a capacity. The length of a slice is the number of elements it contains. The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

How to read and write values to Map

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil.

The following types must NOT be used as a key:

  • function
  • map
  • slice

The comparison operators == and != must be fully defined for operands of the key type.

To get the value from map:

someValue := myMap[key]

Zero value will be returned if no value was found for specified key or a map was not initialized.

To write a value to the initialized map.

myMap[key] = someValue

in case if myMap was not initialized, a panic will occur.

How to get all keys or vals from the Map

Maps in Go don’t have built in functions for retrieving either keys or values. Such funations should be implemented by a developer.

For a map myMap := make(map[string]string) such function will look like:

To retrieve keys:

var myMapKeys []string
for k, _ := range myMap {
    myMapKeys = append(myMapKeys, k)

To retrieve values:

myMapValues := make([]string, 0, len(myMap))
for _, v := range myMapKeys {
    myMapValues = append(myMapValues, v)

Additional resources

comments powered by Disqus