This Go code demonstrates how slices in Go can be...

September 15, 2025 at 07:04 AM

package main import "fmt" func main() { s := []int{2, 3, 5, 7, 11, 13} printSlice(s) // Slice the slice to give it zero length. s = s[:0] printSlice(s) // Extend its length. s = s[:4] printSlice(s) // Drop its first two values. s = s[2:] printSlice(s) } func printSlice(s []int) { fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) }

This Go code demonstrates how slices in Go can be manipulated by altering their length and capacity using slicing operations. Here's a breakdown of what it does:

1. Initial Setup

s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
  • A slice s is initialized with six integers: [2, 3, 5, 7, 11, 13].
  • printSlice(s) is called, which prints the length, capacity, and elements of the slice:
    len=6 cap=6 [2 3 5 7 11 13]
    

2. Slice the slice to zero length

s = s[:0]
printSlice(s)
  • The slice s is updated to have a length of 0 using s[:0]. This operation sets the slice length to zero while keeping the capacity unchanged.
  • printSlice(s) prints:
    len=0 cap=6 []
    

3. Extend the slice length

s = s[:4]
printSlice(s)
  • The slice s is extended back to length 4 using s[:4]. This restores the first four elements of the original slice because the capacity is still 6, allowing the slice to "grow back" up to this limit.
  • printSlice(s) prints:
    len=4 cap=6 [2 3 5 7]
    

4. Drop the first two values

s = s[2:]
printSlice(s)
  • The slice s is updated to drop the first two elements using s[2:]. This operation moves the slice's starting position two steps forward, reducing both its length and capacity relative to the original slice.
  • printSlice(s) prints:
    len=2 cap=4 [5 7]
    

5. The printSlice Function

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
  • This helper function uses fmt.Printf to print the current length, capacity, and elements of a given slice.

Summary of Outputs

When you run the program, the output will be:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

This code illustrates how Go slices are dynamic and can be resized and manipulated while sharing their underlying array.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node