0
0
GoHow-ToBeginner · 3 min read

How to Slice a Slice in Go: Syntax and Examples

In Go, you can slice a slice using the syntax slice[start:end], where start is the starting index (inclusive) and end is the ending index (exclusive). This creates a new slice referencing the original slice's elements between those indices.
📐

Syntax

The basic syntax to slice a slice in Go is slice[start:end]. Here:

  • slice: the original slice you want to slice.
  • start: the index where the new slice begins (inclusive).
  • end: the index where the new slice ends (exclusive).

If start is omitted, it defaults to 0. If end is omitted, it defaults to the length of the slice.

go
newSlice := originalSlice[start:end]
💻

Example

This example shows how to slice a slice of integers to get a part of it.

go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    part := numbers[1:4] // slices from index 1 to 3
    fmt.Println("Original slice:", numbers)
    fmt.Println("Sliced part:", part)
}
Output
Original slice: [10 20 30 40 50] Sliced part: [20 30 40]
⚠️

Common Pitfalls

Common mistakes when slicing a slice include:

  • Using an end index greater than the slice length, which causes a runtime panic.
  • Confusing inclusive and exclusive indices; the end index is not included in the new slice.
  • Modifying the sliced slice also changes the original slice because they share the same underlying array.

Always check slice bounds before slicing to avoid errors.

go
package main

import "fmt"

func main() {
    data := []int{1, 2, 3, 4, 5}
    // Wrong: end index out of range
    // part := data[2:10] // This will panic

    // Correct slicing
    part := data[2:5]
    fmt.Println(part)

    // Modifying part affects original
    part[0] = 99
    fmt.Println("Modified part:", part)
    fmt.Println("Original data:", data)
}
Output
[3 4 5] Modified part: [99 4 5] Original data: [1 2 99 4 5]

Key Takeaways

Use slice[start:end] to create a new slice from an existing one in Go.
The start index is inclusive; the end index is exclusive.
Slicing shares the underlying array, so changes affect both slices.
Avoid out-of-range indices to prevent runtime panics.
Omitting start or end defaults to 0 or the slice length respectively.