DEV Community

Eswar
Eswar

Posted on

Slices in Go

A slice is a data type in Go that represents a sequence of elements of the same type. But the more significant difference with arrays is that the size of a slice is dynamic, not fixed.

A slice has only three components:

  • Pointer to the first reachable element of the underlying array. This element isn't necessarily the array's first element, array[0].
  • Length of the slice. The number of elements in the slice.
  • Capacity of the slice. The number of elements between the start of the slice and the end of the underlying array.

Go

Declare and initialize a slice

package main

import "fmt"

func main() {
    months := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
    fmt.Println(months)
    fmt.Println("Length:", len(months))
    fmt.Println("Capacity:", cap(months))
}
Enter fullscreen mode Exit fullscreen mode

Output


[January February March April May June July August September October November December]
Length: 12
Capacity: 12
Enter fullscreen mode Exit fullscreen mode

Slice items

Go has support for the slice operator s[i:p], where:

s represents the array.
i represents the pointer to the first element of the underlying array (or another slice) to add to the new slice. The variable i corresponds to the element at index location i in the array, array[i]. Remember this element isn't necessarily the underlying array's first element, array[0].
p represents the number of elements in the underlying array to use when creating the new slice. The variable p corresponds to the last element in the underlying array that can be used in the new slice. The element at position p in the underlying array is found at the location array[i+1]. Notice that this element isn't necessarily the underlying array's last element, array[len(array)-1].

Go

package main

import "fmt"

func main() {
    months := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
    quarter1 := months[0:3]
    quarter2 := months[3:6]
    quarter3 := months[6:9]
    quarter4 := months[9:12]
    fmt.Println(quarter1, len(quarter1), cap(quarter1))
    fmt.Println(quarter2, len(quarter2), cap(quarter2))
    fmt.Println(quarter3, len(quarter3), cap(quarter3))
    fmt.Println(quarter4, len(quarter4), cap(quarter4))
} 
Enter fullscreen mode Exit fullscreen mode

Output

[January February March] 3 12
[April May June] 3 9
[July August September] 3 6
[October November December] 3 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)