DEV Community

Henry Arbolaez
Henry Arbolaez

Posted on • Edited on

Keyword make with map & slice

#go

Go provides a built-in map type that implements a hash table.

There are a few advantages of using the keyword make

  • can creates slices, maps and channels
  • create a map or slice with space pre-allocated
  • slice can be with len != capacity
  • zero value of a map is nil

CRU a map with make

  // instantiate a map implicit
  // this will allocated and initialize a hash map
  myMap := make(map[string]string)

  // adding key and value to map
  myMap["city"] = "Miami"

  // retrieving value base on key
  city := myMap["city"]
  // fmt.Println(city) // == "Miami"
Enter fullscreen mode Exit fullscreen mode

CRU a slice with make

  // instantiate a slice implicit
  // this will allocated and initialize a slice with 5 spaces
  mySlice := make([]int, 5) // len(mySlice) == 5

  // you can specify a capacity, pass a third argument to make:
  myCapSlice := make([]int, 3, 5) // len(myCapSlice) == 3, cap(myCapSlice) == 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)