HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to GoVariablesData TypesOperatorsStringsArray & SliceMap (Dictionary)Conditions (if / switch)Loops (for)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Slice
🗂️ Map
🔁 Condition & Loop
🧩 Function
Go›Array & Slice

Array & Slice

Flexible lists (slices), adding with append, and iterating with range.

Simple enough for a 5-year-old to understand

Create slice and append

Example code
1
package main
2
import "fmt"
3
func main() {
4
s := []int{1, 2}
int slice.
Dataint slice.
5
s = append(s, 3)
Append (reassign the result!).
CodeAppend (reassign the result!).
6
fmt.Println(s)
[1 2 3] (with spaces).
Output / Input[1 2 3] (with spaces).
7
}
DataCodeOutput / Input
💡 Hint: The result of append MUST be reassigned: s = append(s, x). Go slices print with spaces: [1 2 3].

About this topic

There are two similar but different structures in Go, and understanding the distinction is one of the turning points of learning Go. An array has a fixed length and the length IS PART OF THE TYPE — a five-element array and a six-element array are different types. A slice, on the other hand, is a growing window opened over an array.

In practice, slices are almost always used in Go code. A slice consists of three things: a pointer to the underlying array, a length, and a capacity. When you add elements with append, if the capacity is sufficient, it writes to the same array; if not, it allocates a larger array and copies the data.

This mechanism is Go's most error-prone corner: two slices can share the same underlying array, and a change you make in one is visible in the other. The fact that append sometimes copies and sometimes doesn't makes this behavior unpredictable.

What you will learn

  • the difference between array and slice
  • creating a slice with make
  • adding elements with append
  • the distinction between len and cap
  • the slice sharing and copying problem
  • taking a safe copy with copy

When to use?

Use a slice if the number of elements changes — which means almost always. An array is preferred only if the size is truly fixed and you want value-copying behavior.

If you know the number of elements beforehand, providing capacity with make prevents append from repeatedly allocating new arrays and makes a measurable difference.

Common mistakes

Wrong

a := []int{1, 2, 3}
b := a
b[0] = 99
fmt.Println(a[0])

Assigning a slice SHARES the underlying array, it does not copy it; changes you make via b are also visible in a, and the output becomes 99. For an independent copy, you need to use copy.

Correct

a := []int{1, 2, 3}
b := make([]int, len(a))
copy(b, a)
b[0] = 99
fmt.Println(a[0])

Wrong

a := []int{1, 2, 3, 4, 5}
b := a[:2]
b = append(b, 99)
fmt.Println(a[2])

Since the capacity of b is still 5, append does not allocate a new array; it overwrites the THIRD element of a, and the output becomes 99. This is Go's most insidious class of bugs. It is necessary to limit capacity using three-index slicing.

Correct

a := []int{1, 2, 3, 4, 5}
b := a[:2:2]
b = append(b, 99)
fmt.Println(a[2])

Wrong

var s []int
s[0] = 1

Writing to a nil slice via indexing crashes the program with "panic: index out of range [0] with length 0". A nil slice can be read and appended to, but cannot be written to via indexing; you must first grow it with append.

Correct

var s []int
s = append(s, 1)
fmt.Println(s[0])

Frequently asked questions

Should I use an array or a slice?

Almost always a slice. Because the array's length is part of its type, it is inflexible and clumsy in function parameters. An array is chosen only if the size is truly fixed or you specifically want value-copying behavior.

What is the difference between len and cap?

len tells you how many elements there are right now, while cap tells you how many elements it can grow up to without allocating a new array. append allocates a new, larger array when len exceeds capacity — and that's precisely where slice sharing breaks.

Why does append sometimes modify the original array?

If the capacity is sufficient, it writes to the same array; if not, it allocates a new array. Thus, the behavior depends on capacity and is unpredictable from the outside. To cut off this risk when passing a slice to another function, use three-index slicing or copy.

Summary

In Go, an array has a fixed length and the length is part of the type; a slice is a growing window and is almost always used in practice. Slices share the underlying array, so an independent copy requires copy and three-index slicing to limit capacity.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code