Go - Maps

Go - Maps

Maps

  1. unordered collection of key/value pairs.

  2. implemented by hash tables.

  3. provide efficient add, get and delete operations.

declaring and initializing a map

  var map_name map[key data type] value data type
  var my_map map[]string int
  package main
  import "fmt"

  func main() {
      var codes map[string]string
      codes["en"] = "English"
      fmt.Println(codes)

  >>> go run main.go
  panic: assignment to entry in nil map

To create a map in key values pair

map_name := map[key data type]value data type{key value pairs}

  codes := map[string]string{"en": "English", "fr": "French"}
  package main
  import "fmt"

  func main() {
      codes := map[string]string{"en": "English", "fr": "French"}
      fmt.Println(codes)
  }
  >>> go run main.go
  map[en:English fr:French]

make() function

main.go

  package main
  import "fmt"

  func main() {
      codes := make(map[string]int)
      fmt.Println(codes)
  }
  >>> go run main.go
  map[]

length of map

  1. len()

accessing a map

  1. map[key]

getting a key

value, found :=map_name[key]

That's great if you have make till here you have covered basic of Golang Maps.

If you liked what you read, do follow and any feedback for further improvement will be highly appreciated!

Thank you and Happy Learning!👏