Explain it simply
Explain it simply
Imagine a long bookshelf, the backing array. A slice is a small card that points at part of that shelf: "starting here, four books, with room for six". The books themselves are not on the card; they live on the shelf.
If two cards point at the same shelf, swapping a book through one card is visible through the other. When the shelf is full, append fetches a bigger shelf, moves the books over and hands you a new card.
Problem → Why → Solution
The problem: the new item vanished
The arrays lesson showed that their length is fixed, so to add items you use a slice and append. But if you call append like JavaScript's push(), Go refuses with "append(languages, "Python") (value of type []string) is not used". And if you store the result in a new variable but keep printing the old one, Python is still missing.
package main
import "fmt"
func main() {
languages := []string{"Go", "JavaScript", "PHP"}
append(languages, "Python") // compile error: value is not used
more := append(languages, "Python")
fmt.Println(len(languages), len(more)) // 3 4
}Why doesn't append change the original slice?
A slice variable is a small header holding a pointer, a length and a capacity, and functions receive a copy of that header. append returns a new header with a longer length, possibly pointing at a brand-new backing array if there was no room. Only languages = append(languages, "Python") makes languages see the new item.
Core concept: a small header over a shared backing array
A slice type is written []T, with no length in the type. A slice value has three parts: a pointer to its first element in a backing array, len, the number of elements currently visible, and cap, the room from that pointer to the end of the array. make([]int, 3, 10) creates a slice with len 3 and cap 10, while []string{"a", "b"} has len and cap 2.
s[low:high] makes a new header that points into the same backing array, covering indexes low through high-1, without copying anything. That is why changing firstTwo[0] after firstTwo := languages[:2] also changes languages[0]. It is the opposite of arrays: pass a slice to a function and the function can edit its elements, and the caller sees those edits.
append(s, x) puts x into the next slot of the backing array when len < cap, and returns a header with a longer len. When len == cap it allocates a larger array, copies the elements across and returns a header pointing at the new array. The caller cannot know in advance which path happens, so always store the result: s = append(s, x). How much the capacity grows is a runtime implementation detail, so never write code that depends on the exact number.
An unassigned var s []int is a nil slice with len 0, and ranging over it or appending to it is perfectly safe. Since Go 1.21 the standard library includes the slices package, so Contains, Index, Sort, Clone, Equal and Delete no longer need hand-written loops.
- Header = pointer + len + cap
- s[a:b] is a new card, same shelf
- append reuses the shelf if room
- No room: new shelf, new card
Two slices can share elements, but each header keeps its own len and cap.
General pattern
var s []T // nil slice, len 0
s := []T{v1, v2} // literal
s := make([]T, length, capacity)
s = append(s, v3, v4) // always store the result
part := s[low:high] // shares the backing array
n := copy(dst, src) // copies min(len(dst), len(src))
slices.Contains(s, v) slices.Index(s, v) slices.Sort(s)
clone := slices.Clone(s) // independent backing arrayAlways store append's result. s[low:high] is a shared view, not a copy; use slices.Clone or copy() when you need an independent one.
Example: append, range and a shared view
This program grows a slice of languages with append and prints it with range. Then it slices off the first two elements, edits that view, and searches with two functions from the slices package. Pay special attention to the "Golang 2" line.
package main
import (
"fmt"
"slices"
)
func main() {
languages := []string{"Go", "JavaScript", "PHP"}
languages = append(languages, "Python")
for index, language := range languages {
fmt.Println(index, language)
}
firstTwo := languages[:2]
firstTwo[0] = "Golang"
fmt.Println(languages[0], len(firstTwo))
fmt.Println(slices.Contains(languages, "PHP"), slices.Index(languages, "Rust"))
}Code breakdown
- Slice literal
languages := []string{"Go", "JavaScript", "PHP"}No length inside the [], so this is a slice, not an array. Go creates a three-element backing array; len and cap are both 3.
- Store append
languages = append(languages, "Python")cap is full, so append moves to a larger array and returns a new header. Storing it back with languages = gives len 4.
- Range
for index, language := range languages {range yields each index and a copy of each element in order, printing four lines from 0 Go to 3 Python.
- Shared view
firstTwo := languages[:2]A new header over indexes 0 and 1, with no data copied. After firstTwo[0] = "Golang", languages[0] is Golang too, and len(firstTwo) is 2.
- slices package
slices.Contains(languages, "PHP"), slices.Index(languages, "Rust")Contains finds PHP and returns true; Index cannot find Rust and returns -1. No hand-written loop needed.
0 Go
1 JavaScript
2 PHP
3 Python
Golang 2
true -1Aliasing: when two appends write the same slot
Suppose base has len 3 and cap 10. append(base, 1) and append(base, 2) both have spare room, so both write to index 3 of the same backing array. The second append overwrites the first, and a[3] and b[3] both read 2. A full slice expression such as base[:3:3] caps the capacity at the length, so each append must allocate its own array and the problem disappears.
package main
import "fmt"
func main() {
base := make([]int, 3, 10)
a := append(base, 1)
b := append(base, 2)
fmt.Println(a[3], b[3]) // 2 2 (same slot!)
safe := base[:3:3] // len 3, cap 3
c := append(safe, 1)
d := append(safe, 2)
fmt.Println(c[3], d[3], len(base), cap(base)) // 1 2 3 10
}nil slices and empty slices
var none []string is nil, while []string{} is an empty slice that is not nil. Both have len 0 and behave the same with range and append, so most code never needs to tell them apart: test emptiness with len(s) == 0. The difference shows up in encoding/json, where a nil slice becomes null and an empty one becomes [], which API clients see differently.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var none []string
empty := []string{}
fmt.Println(none == nil, len(none), empty == nil, len(empty)) // true 0 false 0
none = append(none, "ok")
fmt.Println(none) // [ok]
a, _ := json.Marshal([]string(nil))
b, _ := json.Marshal([]string{})
fmt.Println(string(a), string(b)) // null []
}In real projects
Where this shows up in real projects
In almost every Go program the slice is the most used collection. Reading database rows usually starts with var users []User and does users = append(users, u) inside a rows.Next() loop. Request bodies are read as []byte, strings.Split returns a []string, and command-line arguments live in os.Args, a []string. When you know the row count in advance, make([]User, 0, count) preallocates capacity and avoids repeated reallocation.
Aliasing turns into real production bugs. If one function sorts a slice that came out of a cache, every other piece of code using that cache sees the new order. So when you need to change a slice you do not own, take a copy with slices.Clone first; the challenge's removeItem clones before calling Delete so the caller's cart stays untouched. Likewise, keeping a tiny slice of a huge file's bytes keeps the whole backing array in memory, so clone the small part before storing it long term.
Common mistakes
Common mistakes
1. Appending inside a function and expecting the caller to see it
func addTag(tags []string) { tags = append(tags, "new") } changes only the function's copy of the header, so the caller's len(tags) stays the same. Return the slice instead, func addTag(tags []string) []string, and store it with tags = addTag(tags), exactly like append itself.
2. Assuming a sub-slice is a copy
After top3 := scores[:3], sorting top3 also reorders the first three elements of scores. If there is spare capacity, append(top3, x) can even overwrite scores[3]. When you need your own data, use slices.Clone(scores[:3]).
3. Editing the range variable to change the slice
for _, p := range prices { p *= 2 } doubles a copy of each element, so prices is unchanged. To really edit the elements, use the index: for i := range prices { prices[i] *= 2 }.
Mini challenge
Mini challenge: a shopping cart without duplicates
Write add and remove functions for a shopping cart slice. The remove function must not modify the caller's slice.
- addItem(cart []string, item string) []string returns cart unchanged when the item is already there
- removeItem(cart []string, item string) []string finds the item with slices.Index and deletes from a Clone
- Start from a nil cart (var cart []string) and add rice, eggs, rice, tea
- Print a sorted copy and show that cart keeps its original order
package main
import (
"fmt"
"slices"
)
func addItem(cart []string, item string) []string {
// TODO: skip items that slices.Contains already finds
return cart
}
func removeItem(cart []string, item string) []string {
// TODO: find the index; if missing return cart
// TODO: delete from slices.Clone(cart), never from cart itself
return cart
}
func main() {
var cart []string
// TODO: add "rice", "eggs", "rice", "tea" (store every result!)
// TODO: print cart and len, the cart without "eggs", and a sorted copy
fmt.Println(cart, slices.Contains(cart, "tea"))
}Expected: [rice eggs tea] 3 cart: [rice eggs tea] smaller: [rice tea] sorted: [eggs rice tea]
Show hint
slices.Delete(s, i, i+1) removes index i and returns the slice, but it edits s's backing array in place. That is why you call it on slices.Clone(cart). For sorting, likewise clone first and then call slices.Sort.
Show solution
package main
import (
"fmt"
"slices"
)
func addItem(cart []string, item string) []string {
if slices.Contains(cart, item) {
return cart
}
return append(cart, item)
}
func removeItem(cart []string, item string) []string {
i := slices.Index(cart, item)
if i < 0 {
return cart
}
return slices.Delete(slices.Clone(cart), i, i+1)
}
func main() {
var cart []string
for _, item := range []string{"rice", "eggs", "rice", "tea"} {
cart = addItem(cart, item)
}
fmt.Println(cart, len(cart))
smaller := removeItem(cart, "eggs")
fmt.Println("cart: ", cart)
fmt.Println("smaller:", smaller)
sorted := slices.Clone(cart)
slices.Sort(sorted)
fmt.Println("sorted: ", sorted)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A slice is a header of pointer, len and cap; the elements live in a backing array.
- append returns a new header, so always write s = append(s, x).
- s[low:high] is a shared view, not a copy, so edits show through both; use slices.Clone for an independent copy.
- A nil slice has len 0 and is safe to append to and range over; the slices package provides Contains, Index, Sort and Delete.
A Tour of Go — Go