In this guide, we will look at how to use the make function to create a slice, a map, or a channel.
Golang Make–Create Slice
We can use the built-in make function to create a slice. The make function will create a zeroed array and return a slice referencing an array.
This is a great way to create a dynamically sized array.
To create a slice using the make function, we need to specify three arguments: type, length and the capacity. The function will use these arguments to create the specified slice. Keep in mind is allocated to the array in which the slice references.
The function syntax is as shown:
Consider the example code below:
import "fmt"
func main() {
slice := make([]string, 3, 5)
fmt.Println("Length", len(slice))
fmt.Println("Capacity", cap(slice))
}
In the example above, we create a non-zero slice of length 3 and type string. If we check the length and capacity of the slice and underlying array, respectively, we get:
Capacity 5
Golang Make-Create Map
We can also use the make function to create an empty map. The function syntax for creating a map is as shown:
The example below shows how to create an empty map using the make function.
import "fmt"
func main() {
my_map := make(map[string]string)
// assign
my_map["key_1"] = "value_1"
my_map["key_2"] = "value_2"
fmt.Println(my_map)
}
The above code creates an empty slice and then adds corresponding key and values to the map. We can view the map using the Println function, as shown in the output below:
Golang Make-Create Channel
A channel refers to a pipe that connects concurrent goroutines. Using channels, we can send and receive values into various goroutines.
We can create a channel using the make function as shown in the syntax below:
For example, we can create a simple channel using make as shown in the sample code below:
import "fmt"
func main() {
msg := make(chan string)
go func() {
msg <- "Hi"
}()
message := <-msg
fmt.Println(message)
}
In the above example, we create a channel using the make method. We then send a value into the channel from a new goroutine.
Finally, we receive the value from the channel and prints it out.
Conclusion
In this article, you learned how you can use the built-in make function to create slices, maps and channels in Go.
Thanks for reading & stay tuned for more.