In the Go language, the slice, map and channel types are created with "make," not "new." This function creates a new instance of a slice, map or channel.
The arguments to make indicate what type we are creating, the initial element count, and (optionally) a capacity of the underlying buffer. With a capacity, we can avoid further allocations.
This program uses the make()
built-in in several different ways. And it uses an alternative syntax to create empty slices and maps, without calling make.
make()
calls to create slices, we can use an optional third argument as a hint of what underlying buffer size is desired (a capacity).make()
.package main
import "fmt"
func main() {
// Part 1: use make to create an empty slice, and a 5-element slice of all zero values.
slice1 := make([]int, 0)
slice1 = append(slice1, 10)
fmt.Println("make:", slice1)
slice2 := make([]int, 5)
fmt.Println("make:", slice2)
// Part 2: use make to create a zero-element string slice of capacity 20.
slice3 := make([]string, 0, 20)
slice3 = append(slice3, "cat", "frog", "bird")
fmt.Println("make:", slice3)
// Part 3: a slice can be created without make.
slice4 := []string{}
slice4 = append(slice4, "xyz")
fmt.Println("[]string:", slice4)
// Part 4: use make to create a map with capacity 10.
map1 := make(map[string]int, 10)
map1["abc"] = 1
fmt.Println("make:", map1)
// Part 5: a map can be created without make, but it will not have a custom capacity.
map2 := map[string]int{}
map2["cat"] = 500
fmt.Println("map[string]int:", map2)
// Part 6: use make to create a channel of 10 elements.
channel1 := make(chan int, 10)
channel1 <- 1
channel1 <- 10
fmt.Println("Channel:", len(channel1))
}make: [10]
make: [0 0 0 0 0]
make: [cat frog bird]
[]string: [xyz]
make: map[abc:1]
map[string]int: map[cat:500]
Channel: 2
Make is essentially a new()
method for slices, maps and channels in the Go language. It is unclear why it is not called "new," but make fills this important initialization need.