0
0
Goprogramming~5 mins

Slicing operations in Go

Choose your learning style9 modes available
Introduction
Slicing lets you take a part of a list or array to work with just that piece. It helps you focus on smaller parts without changing the original whole.
You want to get the first few items from a list, like the first 3 names in a list of friends.
You need to skip some items at the start and work with the rest, like ignoring the first 2 days of data.
You want to get a middle section of a list, like days 3 to 5 from a week's data.
You want to copy part of a list to a new list to change it without touching the original.
You want to check or print only a part of a list for easier reading.
Syntax
Go
slice[low:high]
slice[low:]
slice[:high]
slice[:]
low is the start index (included), high is the end index (excluded).
If low is missing, it starts from 0; if high is missing, it goes to the end.
Examples
Gets items from index 1 up to but not including 4 (20, 30, 40).
Go
numbers := []int{10, 20, 30, 40, 50}
part := numbers[1:4]
fmt.Println(part)
Gets items from index 2 to the end ("c", "d").
Go
letters := []string{"a", "b", "c", "d"}
start := letters[2:]
fmt.Println(start)
Gets items from start up to but not including index 2 ("x", "y").
Go
chars := []string{"x", "y", "z"}
end := chars[:2]
fmt.Println(end)
Gets all items, a copy of the whole slice.
Go
all := chars[:]
fmt.Println(all)
Sample Program
This program shows different ways to slice a list of fruits. It prints the first two, a middle part, the last part, and the whole list.
Go
package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry", "date", "fig"}

    firstTwo := fruits[:2]
    middle := fruits[1:4]
    last := fruits[3:]
    all := fruits[:]

    fmt.Println("First two fruits:", firstTwo)
    fmt.Println("Middle fruits:", middle)
    fmt.Println("Last fruits:", last)
    fmt.Println("All fruits:", all)
}
OutputSuccess
Important Notes
Slicing does not copy the data; it creates a view on the original array.
Changing a slice changes the original array if they share the same underlying data.
Be careful with slice bounds to avoid runtime errors (index out of range).
Summary
Slicing extracts parts of a list using start and end indexes.
Start index is included; end index is excluded.
You can omit start or end to slice from the beginning or to the end.