A slice is a dynamically-sized array in Go. Unlike arrays, slices can be resized and have a length that can change at runtime.
Here’s an example of how to declare and use a slice in Go:
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
fmt.Println(a)
b := make([]int, 3, 5)
b[0] = 1
b[1] = 2
b[2] = 3
fmt.Println(b)
c := b[0:2]
fmt.Println(c)
d := c[1:3]
fmt.Println(d)
}
Output:
[1 2 3]
[1 2 3]
[1 2]
[2 3]
You can use the make
function to create a slice with a specified length and capacity:
e := make([]int, 3)
fmt.Println(e)
f := make([]int, 0, 5)
f = append(f, 1, 2, 3)
fmt.Println(f)
Output:
[0 0 0]
[1 2 3]
Note that slices share the same underlying array and changes to one slice will be reflected in the other. To create a new, independent copy of a slice, you can use the copy
function:
g := []int{1, 2, 3}
h := make([]int, len(g))
copy(h, g)
g[0] = 0
fmt.Println(g)
fmt.Println(h)
Output:
[0 2 3]
[1 2 3]
Slices also support several built-in functions for common operations, such as append
, len
, and cap
.
The append
function allows you to add elements to the end of a slice:
i := []int{1, 2, 3}
i = append(i, 4, 5, 6)
fmt.Println(i)
Output:
[1 2 3 4 5 6]
The len
function returns the length of a slice, and the cap
function returns the capacity of a slice:
j := []int{1, 2, 3}
fmt.Println(len(j), cap(j))
k := make([]int, 3, 5)
fmt.Println(len(k), cap(k))
Output:
3 3
3 5
Slices are a powerful and flexible data structure in Go, and are used extensively in many applications.
Leave a Reply