How to Use make for Slice in Go: Syntax and Examples
In Go, you use
make to create a slice by specifying its type, length, and optionally capacity like make([]Type, length, capacity). This allocates the slice with the given length and capacity, ready to use.Syntax
The make function creates slices with a specified length and optional capacity.
- Type: The slice element type inside square brackets, e.g.,
[]int. - Length: Number of elements the slice initially holds.
- Capacity (optional): Total space allocated for the slice, must be >= length.
go
slice := make([]int, length, capacity)Example
This example creates a slice of integers with length 3 and capacity 5, then prints its length, capacity, and contents.
go
package main import "fmt" func main() { // Create a slice of int with length 3 and capacity 5 s := make([]int, 3, 5) // Print length and capacity fmt.Println("Length:", len(s)) fmt.Println("Capacity:", cap(s)) // Print the slice contents (zero values) fmt.Println("Slice contents:", s) // Assign values to slice elements s[0] = 10 s[1] = 20 s[2] = 30 fmt.Println("Updated slice:", s) }
Output
Length: 3
Capacity: 5
Slice contents: [0 0 0]
Updated slice: [10 20 30]
Common Pitfalls
Common mistakes when using make for slices include:
- Setting capacity smaller than length causes a compile-time error.
- Accessing elements beyond the length causes a runtime panic.
- Confusing length and capacity: length is how many elements are accessible, capacity is total allocated space.
go
package main import "fmt" func main() { // Wrong: capacity less than length (compile error) // s := make([]int, 5, 3) // Uncommenting causes error // Right: capacity >= length s := make([]int, 3, 5) // Wrong: accessing beyond length causes panic // fmt.Println(s[4]) // Uncommenting causes runtime panic // Right: access only within length fmt.Println(s[2]) }
Output
0
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| Type | Element type of the slice | []int, []string |
| Length | Initial number of elements | 3 |
| Capacity | Total allocated space (optional) | 5 |
| Usage | Create slice with length and capacity | make([]int, 3, 5) |
Key Takeaways
Use make([]Type, length, capacity) to create slices with specified size and space.
Length is how many elements you can use; capacity is total allocated space.
Capacity must be equal or larger than length, or Go will error.
Accessing elements beyond length causes runtime panic.
make initializes slice elements with zero values of the element type.