Level: BeginnerGo Programs

Go Slice Programs with Output: Append, Remove, Merge, Rotate

Updated 16 min read
Go Slice Programs featured image: append, capacity and chunk output

Go slice programs work with lists that can grow and shrink, which is how Go stores almost every collection, from cart items to log lines. In this post, you will write fourteen slice programs with their exact output, covering append, remove, insert, duplicates, merge, rotate and chunking. Then you will practice the slice questions that catch even experienced developers, such as the shared array trap.

You should first read our Go array programs, because every slice sits on top of an array. For the full theory, see Go slices and arrays explained. All programs use the slices package from the standard library and were tested on Go 1.27.

What are Go Slice Programs?

Go slice programs use a slice, which is a small view onto an array. A slice has three parts: a pointer to the first item, a length (how many items you can see) and a capacity (how many items fit before Go needs a new array).

Think of a slice as a window on a long bookshelf. The shelf is the array. The window shows some books, and you can slide or widen it. If you need more space than the shelf has, Go buys a bigger shelf and moves the books.

Why Go Slice Programs Matter

You will use slices in almost every Go file. For example, an API returns a slice of users, a file reader collects a slice of lines and a cart holds a slice of items. So Go slice programs are a core part of every Go interview.

  • Everyday work: append, filter and sort are daily tasks.
  • Memory bugs: sharing an array between slices causes surprising changes.
  • Interviews: remove duplicates, rotate and merge are standard questions.

How Go Slice Programs Work

When you append to a slice, Go checks the capacity. If there is room, it writes into the same array. If not, it makes a bigger array, copies the items and returns a slice that points to the new array.

Go slice programs diagram showing pointer, length and capacity over an array
A slice holds a pointer, a length and a capacity, and append makes a new array only when the capacity is full.

The table below lists the slice tools used in this post.

ToolWhat it doesSince
append(s, v…)Adds items at the endAlways
make([]T, len, cap)Creates a slice with spaceAlways
copy(dst, src)Copies items, returns the countAlways
slices.Insert / DeleteAdds or removes in the middleGo 1.21
slices.Contains / IndexFinds an itemGo 1.21
slices.Sort / Compact / ReverseSorts, removes repeats, flipsGo 1.21
slices.ChunkSplits into batchesGo 1.23

Basic Go Slice Programs

These first Go slice programs create slices and grow them.

Program 1: Create Slices Three Ways

package main

import "fmt"

func main() {
    // Way 1: a slice with values. [] with no number means "slice", not array.
    // := creates a variable and gives it a value in one go.
    prices := []int{10, 20, 30}

    // Way 2: make([]int, length, capacity) gives 3 zeros with room for 5.
    scores := make([]int, 3, 5)

    // Way 3: declare a slice with no value. It is nil (empty, no array yet).
    var empty []int

    // len = items you can see, cap = items that fit before Go needs a new array.
    fmt.Println(prices, len(prices), cap(prices))
    fmt.Println(scores, len(scores), cap(scores))
    fmt.Println(empty, len(empty), cap(empty), empty == nil)
}
[10 20 30] 3 3
[0 0 0] 3 5
[] 0 0 true

The first slice holds three values, so its length and capacity are both 3. Next, make([]int, 3, 5) gives 3 visible zeros with room for 5. A declared slice with no value is nil, but it still prints as [] and works with append.

Program 2: Append and Watch Capacity Grow

package main

import "fmt"

func main() {
    var numbers []int
    for i := 1; i <= 5; i++ {
        // append adds an item at the end and returns the updated slice.
        // Always save the result back into the variable.
        numbers = append(numbers, i*10)
        fmt.Println(numbers, "len:", len(numbers), "cap:", cap(numbers))
    }
}
[10] len: 1 cap: 1
[10 20] len: 2 cap: 2
[10 20 30] len: 3 cap: 4
[10 20 30 40] len: 4 cap: 4
[10 20 30 40 50] len: 5 cap: 8

Each turn of the loop adds one number. When the slice is full, Go makes a bigger array, so the capacity jumps from 2 to 4 and then to 8. Always assign the result, as in numbers = append(numbers, ...), because it may return a new slice.

Program 3: Read, Change and Loop Over a Slice

This easy program shows the three things you do most with a slice.

package main

import "fmt"

func main() {
    colors := []string{"red", "green", "blue"}

    // Step 1: read one item by its index. Indexes start at 0.
    fmt.Println("First color:", colors[0])

    // Step 2: change one item.
    colors[1] = "yellow"

    // Step 3: visit every item.
    // range gives the index and the value on each turn.
    for index, color := range colors {
        fmt.Println(index, color)
    }
}
First color: red
0 red
1 yellow
2 blue

First, colors[0] reads the item at position 0. Then colors[1] = "yellow" replaces “green”. Finally, the range loop prints each index with its value.

Changing Go Slice Programs

These Go slice programs add, remove and rearrange items.

Program 4: Remove an Item at an Index

package main

import (
    "fmt"
    "slices"
)

func main() {
    // Way 1: the slices package.
    // slices.Delete(list, from, to) removes items from index "from" up to, not including, "to".
    fruits := []string{"apple", "banana", "cherry", "date"}
    fruits = slices.Delete(fruits, 1, 2) // remove index 1
    fmt.Println(fruits, len(fruits))

    // Way 2: the classic append trick you will see in older code.
    numbers := []int{5, 6, 7, 8}
    index := 2
    // numbers[:index] is the part before the item: [5 6]
    // numbers[index+1:] is the part after the item: [8]
    // ... spreads the second slice into separate values.
    numbers = append(numbers[:index], numbers[index+1:]...)
    fmt.Println(numbers)
}
[apple cherry date] 3
[5 6 8]

slices.Delete removes “banana” at index 1, so three fruits are left. The classic way joins the part before index 2 with the part after it. Both ways skip the item you want to remove.

Program 5: Insert an Item at an Index

package main

import (
    "fmt"
    "slices"
)

func main() {
    queue := []string{"Asha", "Ravi", "Meera"}

    // slices.Insert(list, index, value) puts value at index
    // and pushes the later items one place to the right.
    queue = slices.Insert(queue, 1, "Kiran")
    fmt.Println(queue)
}
[Asha Kiran Ravi Meera]

slices.Insert puts “Kiran” at index 1. Then “Ravi” and “Meera” move one place to the right. As with append, you save the result back into queue.

Program 6: Remove Duplicates

Here are two ways. The first keeps the original order, and the second sorts first.

package main

import (
    "fmt"
    "slices"
)

// uniqueKeepOrder returns the numbers without repeats, in their first-seen order.
func uniqueKeepOrder(numbers []int) []int {
    // seen remembers which numbers we already added. A missing key reads as false.
    seen := map[int]bool{}
    var result []int
    for _, number := range numbers { // _ skips the index we do not need
        if !seen[number] {
            seen[number] = true
            result = append(result, number)
        }
    }
    return result
}

func main() {
    data := []int{4, 2, 4, 9, 2, 7, 9}
    fmt.Println(uniqueKeepOrder(data))

    // Way 2: copy, sort, then remove repeats that sit next to each other.
    sorted := slices.Clone(data) // a new copy, so data stays the same
    slices.Sort(sorted)
    fmt.Println(slices.Compact(sorted))
}
[4 2 9 7]
[2 4 7 9]

The first way uses a map to remember each number it has seen. It adds a number only the first time, so the order stays the same. slices.Compact only removes repeats that sit next to each other, so you sort first.

Program 7: Merge Two Slices

package main

import "fmt"

func main() {
    morning := []string{"tea", "toast"}
    evening := []string{"soup", "rice", "curd"}

    // evening... spreads the slice into separate values for append.
    meals := append(morning, evening...)
    fmt.Println(meals, len(meals))
}
[tea toast soup rice curd] 5

append takes the first slice and adds the items that follow it. The ... spreads the second slice into separate values. So all five meals end up in one slice.

Program 8: Rotate a Slice

package main

import (
    "fmt"
    "slices"
)

// rotateLeft moves the first "steps" items to the end and returns a new slice.
func rotateLeft(numbers []int, steps int) []int {
    // Step 1: rotating 5 items by 7 is the same as rotating by 2.
    // % gives the remainder after division.
    steps = steps % len(numbers)

    // Step 2: take the back part, then add the front part after it.
    back := slices.Clone(numbers[steps:]) // copy, so the original stays safe
    front := numbers[:steps]
    return append(back, front...)
}

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println(rotateLeft(numbers, 2))
    fmt.Println(rotateLeft(numbers, 7))
    fmt.Println(numbers)
}
[3 4 5 1 2]
[3 4 5 1 2]
[1 2 3 4 5]

The remainder means a rotation by 7 is the same as by 2 for five items. Then the function joins the back part [3 4 5] with the front part [1 2]. slices.Clone keeps the original slice safe.

Program 9: Filter Even Numbers

package main

import (
    "fmt"
    "slices"
)

// isEven reports whether a number divides by 2 with no remainder.
func isEven(number int) bool {
    return number%2 == 0
}

func main() {
    numbers := []int{3, 8, 15, 22, 7, 10}

    // Way 1: a loop that keeps only the even numbers.
    var evens []int
    for _, number := range numbers {
        if isEven(number) {
            evens = append(evens, number)
        }
    }
    fmt.Println(evens)

    // Way 2: slices.DeleteFunc removes every item where isEven returns true.
    // We clone first, so numbers itself is not changed.
    odds := slices.DeleteFunc(slices.Clone(numbers), isEven)
    fmt.Println(odds)
}
[8 22 10]
[3 15 7]

The loop builds a new slice that holds only the evens. slices.DeleteFunc does the opposite job. It removes every item where isEven returns true, so only the odds are left.

Searching and Splitting Go Slice Programs

The next Go slice programs find items and break a slice into pieces.

Program 10: Find, Contains and Index

package main

import (
    "fmt"
    "slices"
)

func main() {
    languages := []string{"Go", "Python", "Rust", "Java"}

    fmt.Println(slices.Contains(languages, "Rust")) // true if the item is there
    fmt.Println(slices.Index(languages, "Java"))    // position of the item
    fmt.Println(slices.Index(languages, "C"))       // -1 means not found

    marks := []int{4, 19, 7}
    fmt.Println(slices.Max(marks), slices.Min(marks))
}
true
3
-1
19 4

slices.Contains answers yes or no, so it prints true for “Rust”. slices.Index gives the position, which is 3 for “Java”. If the item is missing, it returns -1.

Program 11: Count Items That Match a Rule

This simple program counts how many words are longer than four letters.

package main

import "fmt"

func main() {
    words := []string{"go", "slice", "map", "append", "loop"}
    count := 0

    for _, word := range words {
        // len of a string gives its number of bytes, which is letters for plain English.
        if len(word) > 4 {
            count++
            fmt.Println("Long word:", word)
        }
    }
    fmt.Println("Total long words:", count)
}
Long word: slice
Long word: append
Total long words: 2

The loop checks the length of each word. When a word has more than four letters, you add one to count and print it. At the end, count holds 2.

Program 12: Split into Chunks

slices.Chunk returns an iterator, so you loop over it with range.

package main

import (
    "fmt"
    "slices"
)

func main() {
    orders := []int{101, 102, 103, 104, 105, 106, 107}

    // slices.Chunk hands out groups of 3 items, one group per loop turn.
    for batch := range slices.Chunk(orders, 3) {
        fmt.Println(batch)
    }
}
[101 102 103]
[104 105 106]
[107]

Each turn of the loop gets the next group of three orders. The last chunk can be shorter. This is useful for sending records to an API in batches.

Program 13: Reverse and Check Equality

package main

import (
    "fmt"
    "slices"
)

func main() {
    numbers := []int{1, 2, 3, 2, 1}

    reversed := slices.Clone(numbers) // copy first, so numbers stays the same
    slices.Reverse(reversed)          // flips the copy in place

    // slices.Equal checks the same length and the same items in order.
    fmt.Println(reversed, slices.Equal(numbers, reversed))
}
[1 2 3 2 1] true

You copy the slice, then flip the copy. A slice that equals its reverse is a palindrome. Slices cannot be compared with ==, so you use slices.Equal.

Program 14: A 2D Slice for a Seating Chart

package main

import "fmt"

func main() {
    rows := 3
    cols := 4

    // Step 1: make the outer slice, one entry per row.
    seats := make([][]string, rows)

    // Step 2: make each row and fill it with "." (empty seat).
    for i := range seats {
        seats[i] = make([]string, cols)
        for j := range seats[i] {
            seats[i][j] = "."
        }
    }

    // Step 3: book row 1, seat 2.
    seats[1][2] = "X"
    for _, row := range seats {
        fmt.Println(row)
    }
}
[. . . .]
[. . X .]
[. . . .]

First, you make the outer slice with three rows. Then each row gets its own slice of four seats. Rows could even have different lengths, and you will use this in the matrix programs later in this level.

Copy vs Share in Go Slice Programs

The biggest trap in Go slice programs is sharing an array without knowing it. The diagram and table below compare sharing with copying.

Go slice programs comparison of shared slices and copied slices
Slicing shares the same array, so changes show in both, while copy or slices.Clone gives each slice its own data.
FeatureShare (b := a[1:3])Copy (copy or slices.Clone)
MemorySame arrayNew array
Change b[0]Also changes aa stays the same
SpeedInstantCopies every item
RiskSurprise changesNone
Use whenRead-only viewsYou will change the data

So slice freely for read-only work, and clone before you change data that someone else also uses.

Common Mistakes in Go Slice Programs

  • Not assigning append: append(s, 5) alone does nothing useful. Write s = append(s, 5).
  • Sharing by accident: a sub-slice changes the original array, so clone it when you need a safe copy.
  • Comparing with ==: slices only compare with nil. Use slices.Equal.
  • Compact without sort: slices.Compact removes only neighbours, so sort first for full de-duplication.
  • Index out of range: s[len(s)] panics, so check the length before you read.

Best Practices for Go Slice Programs

  • Use the slices package for insert, delete, sort and search, since it is tested and clear.
  • Preallocate with make when you know the size, to avoid repeated growth.
  • Return new slices from functions, and let callers assign the result.
  • Clone before you change data that came from somewhere else.
  • Use nil slices freely, because len, range and append all work on them.

Go Slice Programs Interview Questions and Answers

Interviewers ask these Go slice programs more than any other collection questions. Each program is complete, with real output from Go 1.27.

Length and Capacity in Go Slice Programs

Q1. What does this program print?

package main

import "fmt"

func main() {
    numbers := [6]int{0, 1, 2, 3, 4, 5} // an array of 6 items
    part := numbers[1:4]                // from index 1 up to, not including, 4
    fmt.Println(part, len(part), cap(part))
}
[1 2 3] 3 5

The slice starts at index 1 and stops before 4, so it has 3 items. Its capacity runs to the end of the array, which leaves 5 slots.

Q2. What does this program print?

package main

import "fmt"

func main() {
    original := []int{1, 2, 3, 4}
    part := original[:2] // [1 2], but it shares the same array
    part = append(part, 99)
    fmt.Println(original, part)
}
[1 2 99 4] [1 2 99]

part still had room in the same array, so append wrote 99 over original[2]. This is the most famous slice trap in Go.

Q3. How do you stop append from overwriting the original?

package main

import "fmt"

func main() {
    original := []int{1, 2, 3, 4}
    // Full slice expression [low:high:max]: here the capacity is 2 - 0 = 2.
    part := original[:2:2]
    part = append(part, 99) // no spare room, so append makes a new array
    fmt.Println(original, part)
}
[1 2 3 4] [1 2 99]

The third number in original[:2:2] sets the capacity. With no spare room, append has to make a new array, so original stays safe.

nil and Empty Questions

Q4. What is the difference between a nil slice and an empty slice?

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var nilSlice []int    // no array at all
    emptySlice := []int{} // an array with zero items
    fmt.Println(nilSlice == nil, emptySlice == nil, len(nilSlice), len(emptySlice))

    // json.Marshal turns a value into JSON bytes.
    // It also returns an error, which we skip here with _.
    nilJSON, _ := json.Marshal(nilSlice)
    emptyJSON, _ := json.Marshal(emptySlice)
    fmt.Println(string(nilJSON), string(emptyJSON))
}
true false 0 0
null []

Both have length 0 and work the same in Go code. However, JSON shows a nil slice as null and an empty one as [], which matters for APIs.

Q5. What does this program print?

package main

import "fmt"

func main() {
    source := []int{1, 2, 3, 4, 5}
    destination := make([]int, 3)
    copied := copy(destination, source) // returns how many items were copied
    fmt.Println(copied, destination)
}
3 [1 2 3]

copy stops at the shorter slice and returns how many items it copied. Here destination has room for 3, so only 3 items move.

Function and Output Questions

Q6. What does this program print?

package main

import "fmt"

// change edits the first item, then appends a new one.
func change(numbers []int) {
    numbers[0] = 100             // changes the shared array
    numbers = append(numbers, 4) // no room, so this makes a new array only change sees
}

func main() {
    numbers := []int{1, 2, 3}
    change(numbers)
    fmt.Println(numbers)
}
[100 2 3]

The function gets a copy of the slice header, which still points to the same array. So numbers[0] = 100 changes the caller’s data. But the append makes a new array that the caller never sees.

Q7. Why does this program panic?

package main

import "fmt"

func main() {
    numbers := make([]int, 0, 10) // length 0, room for 10
    fmt.Println(numbers[0])
}
panic: runtime error: index out of range [0] with length 0

Capacity is not length. The slice has room for 10 items but holds none, so index 0 does not exist yet.

Q8. What does this program print?

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}
    clear(numbers) // sets every item to zero
    fmt.Println(numbers, len(numbers))

    numbers = numbers[:0] // hide all items, but keep the array
    fmt.Println(numbers, len(numbers), cap(numbers))
}
[0 0 0] 3
[] 0 3

The built-in clear sets every item to zero but keeps the length. numbers[:0] keeps the array and capacity but hides all items, which lets you reuse the memory.

Q9. What does this program print?

package main

import "fmt"

func main() {
    var grid [][]int // a slice of slices
    grid = append(grid, []int{1, 2})
    grid = append(grid, []int{3})
    fmt.Println(grid, len(grid), len(grid[1]))
}
[[1 2] [3]] 2 1

Rows in a 2D slice can have different lengths. This is called a jagged slice.

Q10. What does this program print?

package main

import (
    "fmt"
    "slices"
)

func main() {
    letters := []string{"b", "a", "c"}
    // slices.Values hands out each item, and slices.Sorted collects them into a new sorted slice.
    sorted := slices.Sorted(slices.Values(letters))
    fmt.Println(letters, sorted)
}
[b a c] [a b c]

slices.Sorted returns a new sorted slice, so the original keeps its order. slices.Sort would sort letters itself.

Q11. Can a slice be a map key?

No. Slices are not comparable, so Go rejects them as keys at compile time. Use an array, a string or a struct of comparable fields instead.

Q12. How do you preallocate a slice for 1,000 items?

Write s := make([]int, 0, 1000) and then append. The length starts at 0, but there is room for 1,000 items, so no copies happen while you fill it.

Practice Task

This task combines three Go slice programs from above. Write a function that takes a slice of order amounts and returns a new slice with only the orders above 500, sorted from highest to lowest. Hint: filter first, then use slices.Sort followed by slices.Reverse.

Official Resources

Quick Recap

  • Go slice programs use a view with a pointer, a length and a capacity.
  • Always assign the result of append, because it may return a new array.
  • Sub-slices share memory, so clone before you change shared data.
  • The slices package gives you Insert, Delete, Contains, Sort, Compact and Chunk.
  • A nil slice and an empty slice behave the same in Go, but differ in JSON.

What’s Next?

Next, we put slices in order. Read Go sorting programs with output, with bubble, selection, insertion, merge and quick sort. To revise the interview side of slices, see the Go slice interview questions.