Create Slice in Go #
Slices in Go are flexible, dynamic sequences that provide more functionality than arrays. There are several ways to create a slice, depending on your use case.
1. Create a Slice Using []datatype{values}
#
The simplest way to declare a slice is using the []datatype{values}
syntax.
Syntax:
slice_name := []datatype{values}
Examples:
package main
import ("fmt")
func main() {
myslice1 := []int{} // Empty slice
fmt.Println(len(myslice1)) // 0
fmt.Println(cap(myslice1)) // 0
fmt.Println(myslice1) // []
myslice2 := []string{"Go", "Slices", "Are", "Powerful"}
fmt.Println(len(myslice2)) // 4
fmt.Println(cap(myslice2)) // 4
fmt.Println(myslice2) // [Go Slices Are Powerful]
}
Explanation:
myslice1
has no elements, so both length and capacity are 0.myslice2
has 4 elements, so length and capacity are both 4.
2. Create a Slice From an Array #
A slice can be created by slicing an existing array.
Syntax:
var myarray = [length]datatype{values}
myslice := myarray[start:end]
Example:
package main
import ("fmt")
func main() {
arr1 := [6]int{10, 11, 12, 13, 14, 15}
myslice := arr1[2:4]
fmt.Printf("myslice = %v\n", myslice)
fmt.Printf("length = %d\n", len(myslice))
fmt.Printf("capacity = %d\n", cap(myslice))
}
Result:
myslice = [12 13]
length = 2
capacity = 4
Explanation:
- The slice starts from the third element (
arr1[2]
) and ends before the fifth element (arr1[4]
). - Length is the number of elements in the slice.
- Capacity is the number of elements from the starting index to the end of the array.
3. Create a Slice With the make()
Function
#
The make()
function allows you to create a slice with a defined length and capacity.
Syntax:
slice_name := make([]type, length, capacity)
- If
capacity
is omitted, it defaults to thelength
.
Example:
package main
import ("fmt")
func main() {
myslice1 := make([]int, 5, 10)
fmt.Printf("myslice1 = %v\n", myslice1)
fmt.Printf("length = %d\n", len(myslice1))
fmt.Printf("capacity = %d\n", cap(myslice1))
myslice2 := make([]int, 5) // capacity omitted
fmt.Printf("myslice2 = %v\n", myslice2)
fmt.Printf("length = %d\n", len(myslice2))
fmt.Printf("capacity = %d\n", cap(myslice2))
}
Result:
myslice1 = [0 0 0 0 0]
length = 5
capacity = 10
myslice2 = [0 0 0 0 0]
length = 5
capacity = 5
Explanation:
myslice1
has length 5 but capacity 10, allowing it to grow up to 10 elements without reallocation.myslice2
has length and capacity equal to 5.
Slices are a versatile way to work with sequences in Go. Next, you can learn how to modify slices including appending, copying, and deleting elements.