Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active July 13, 2021 16:09
Show Gist options
  • Save davidlares/57ef0c4c7e4915c3a62991226f29e9fd to your computer and use it in GitHub Desktop.
Save davidlares/57ef0c4c7e4915c3a62991226f29e9fd to your computer and use it in GitHub Desktop.
Maps in Golang
package main
import "fmt"
// Map
func main() {
// statically type [key]values{}
colors := map[string]string{
"red": "#ff0000",
"green": "#7845AF",
}
// printing colors
fmt.Println(colors)
// another way of declaring
// var colores map[string]string // init empty by default
// another way (builtin function)
colores2 := make(map[string]string)
// adding values - always use brackers
colores2["white"] = "#ffffff"
// delete (element, key)
delete(colores2, "white")
// printing
printMap(colors)
}
// iterating map
func printMap(c map[string]string) {
for color, hex := range c {
fmt.Println("Hex code for", color, "is", hex)
}
}

Maps in Golang

This is a very similar data type as structs, but it has certain differences.

The keys and values of the map are statically typed (All the same type!)

Here's a definition: m map[string] string where the m is the argument name and the [string] is the type of the map.

Characteristics of the Maps

  1. All keys must be the same type
  2. All values must be the same type
  3. Keys are indexed, we can add an iterator over them
  4. Is used to represent a collection of related properties
  5. Doesn't need to know all the keys at compile time
  6. Most important: is a reference data type

And compared to Structs, we have:

  1. Values can be of different types in terms of keys and values
  2. Keys does not support indexing
  3. You need to know all the different fields at compile time.
  4. Is used to represent a "thing" with a lot of different properties.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment