Home »
Golang »
Golang Reference
Golang make() Function with Examples
Golang | make() Function: Here, we are going to learn about the built-in make() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 17, 2021 [Last updated : March 15, 2023]
make() Function
In the Go programming language, the make() is a built-in function that is used to allocate and initializes an object of type slice, map, or chan (only). The return type of the make() function is the same as the type of its argument, not a pointer to it.
The specification of the result depends on the type:
- Slice: The size specifies the length. The capacity of the slice is equal to its length. A second integer argument may be provided to specify a different capacity; it must be no smaller than the length.
For example, make([]int, 0, 10) allocates an underlying array of size 10 and returns a slice of length 0 and capacity 10 that is backed by this underlying array.
- Map: An empty map is allocated with enough space to hold the specified number of elements. The size may be omitted, in which case a small starting size is allocated.
- Channel: The channel's buffer is initialized with the specified buffer capacity. If zero, or the size is omitted, the channel is unbuffered.
It accepts two or more parameters (t Type, size ...IntegerType) and returns the type of its arguments (parameter).
Syntax
func make(t Type, size ...IntegerType) Type
Parameter(s)
- t : The type.
- size… : The size and capacity.
Return Value
The return type of the make() function is Type, it returns the type of its arguments (parameter).
Example 1
// Golang program to demonstrate the
// example of make() function
package main
import (
"fmt"
)
func main() {
a := make([]int, 5)
fmt.Printf("a: Type: %T, Length: %d, Capacity: %d\n",
a, len(a), cap(a))
fmt.Println("value of a:", a)
b := make([]int, 10, 20)
fmt.Printf("b: Type: %T, Length: %d, Capacity: %d\n",
b, len(b), cap(b))
fmt.Println("value of b:", b)
c := make([]int, 0, 5)
fmt.Printf("c: Type: %T, Length: %d, Capacity: %d\n",
c, len(c), cap(c))
fmt.Println("value of c:", c)
}
Output
a: Type: []int, Length: 5, Capacity: 5
value of a: [0 0 0 0 0]
b: Type: []int, Length: 10, Capacity: 20
value of b: [0 0 0 0 0 0 0 0 0 0]
c: Type: []int, Length: 0, Capacity: 5
value of c: []
Example 2
// Golang program to demonstrate the
// example of make() function
package main
import (
"fmt"
)
func main() {
// Creating a map using make()
var student = make(map[string]int)
// Assigning
student["Alvin"] = 21
student["Alex"] = 47
student["Mark"] = 27
// Printing the map, its type and lenght
fmt.Println(student)
fmt.Printf("Type: %T, Length: %d\n",
student, len(student))
}
Output
map[Alex:47 Alvin:21 Mark:27]
Type: map[string]int, Length: 3
Golang builtin Package »