DEV Community

loading...

Keyword make with map & slice

#go
Henry Arbolaez
I'm a coffee lover, thinker, and a software engineer. I'm passionate about the idea of bringing people together to collaborate, to build a great product.
Updated on ・1 min read

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

Discussion (0)