How to Create Slice in Go: Syntax and Examples
In Go, you create a
slice using the built-in make function or by slicing an existing array or slice with array[start:end]. Slices are dynamic, flexible views into arrays that can grow and shrink as needed.Syntax
There are two main ways to create a slice in Go:
- Using
make:make([]Type, length, capacity)creates a slice with a specified length and optional capacity. - Slicing an array or slice:
array[start:end]creates a slice referencing elements fromstartup to but not includingend.
go
var s1 []int = make([]int, 5) // slice of int with length 5 arr := [5]int{1, 2, 3, 4, 5} s2 := arr[1:4] // slice referencing elements 2,3,4
Example
This example shows how to create slices using make and by slicing an array, then prints their contents and lengths.
go
package main import "fmt" func main() { // Create slice with make s1 := make([]int, 3, 5) // length 3, capacity 5 s1[0], s1[1], s1[2] = 10, 20, 30 // Create slice by slicing an array arr := [5]int{1, 2, 3, 4, 5} s2 := arr[1:4] // elements 2,3,4 fmt.Println("Slice s1:", s1) fmt.Println("Length of s1:", len(s1)) fmt.Println("Capacity of s1:", cap(s1)) fmt.Println("Slice s2:", s2) fmt.Println("Length of s2:", len(s2)) fmt.Println("Capacity of s2:", cap(s2)) }
Output
Slice s1: [10 20 30]
Length of s1: 3
Capacity of s1: 5
Slice s2: [2 3 4]
Length of s2: 3
Capacity of s2: 4
Common Pitfalls
Common mistakes when creating slices include:
- Confusing slice length and capacity; length is how many elements are accessible, capacity is how many elements can be stored before resizing.
- Trying to access elements beyond the slice length causes a runtime panic.
- Modifying a slice created from an array changes the original array since slices reference the same underlying data.
go
package main import "fmt" func main() { s := make([]int, 2) // length 2 // Wrong: accessing index 2 causes panic // fmt.Println(s[2]) arr := [3]int{1, 2, 3} slice := arr[0:2] slice[0] = 100 fmt.Println("Modified slice:", slice) fmt.Println("Original array:", arr) }
Output
Modified slice: [100 2]
Original array: [100 2 3]
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Create slice with make | make([]Type, length, capacity) | Creates a slice with given length and optional capacity |
| Slice from array | array[start:end] | Creates a slice referencing elements from start to end-1 |
| Length | len(slice) | Number of elements accessible in the slice |
| Capacity | cap(slice) | Maximum number of elements slice can grow to without reallocating |
Key Takeaways
Use make([]Type, length, capacity) to create slices with specified size and capacity.
Slices are views into arrays and share the underlying data.
Length is how many elements you can access; capacity is how many elements can fit before resizing.
Accessing beyond slice length causes a runtime error.
Modifying a slice affects the original array if the slice references it.