0
0
Goprogramming~5 mins

Common slice operations in Go

Choose your learning style9 modes available
Introduction

Slices let you work with lists of items easily. Common slice operations help you add, remove, or change items in these lists.

You want to add a new item to a list of names.
You need to remove an item from a list of numbers.
You want to get a part of a list, like the first three items.
You want to find how many items are in a list.
You want to change an item in a list.
Syntax
Go
var s []Type

// Add item
s = append(s, item)

// Remove item at index i
s = append(s[:i], s[i+1:]...)

// Get slice from index start to end-1
sub := s[start:end]

// Length of slice
length := len(s)

append adds items to the end of a slice.

Removing an item uses append to join parts before and after the item.

Examples
Adds 4 to the end of the numbers slice.
Go
numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
Removes the item at index 2 ("c") from letters.
Go
letters := []string{"a", "b", "c", "d"}
letters = append(letters[:2], letters[3:]...)
Gets a new slice with items from index 1 to 2 ("banana", "cherry").
Go
items := []string{"apple", "banana", "cherry", "date"}
sub := items[1:3]
Finds how many items are in the slice.
Go
count := len(items)
Sample Program

This program shows how to add, remove, slice, and count items in a slice of fruits.

Go
package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry"}
    fmt.Println("Original slice:", fruits)

    // Add a fruit
    fruits = append(fruits, "date")
    fmt.Println("After append:", fruits)

    // Remove the second fruit (index 1)
    fruits = append(fruits[:1], fruits[2:]...)
    fmt.Println("After removal:", fruits)

    // Get a slice of first two fruits
    firstTwo := fruits[:2]
    fmt.Println("First two fruits:", firstTwo)

    // Length of slice
    fmt.Println("Number of fruits:", len(fruits))
}
OutputSuccess
Important Notes

Remember slices are like windows to arrays; changing a slice can affect the underlying array.

Use append carefully to avoid unexpected results when removing items.

Summary

Slices hold lists of items you can change easily.

Use append to add or remove items.

You can get parts of slices using slicing syntax [start:end].