Go uses two closely related ways to store sequences of values. An array has a fixed length that forms part of its type. A slice is a variable-length view over an underlying array. The distinction determines how programs allocate memory, pass data into functions, and react when new elements are appended. A slice may share storage with an array or another slice, so a change that looks local can also affect other variables. The official Go slice internals guide explains the storage model.
The Go curriculum previously introduced typed functions and error results, control flow, and types and zero values. Arrays and slices supply collections to those functions and loops. The curriculum registry identifies the progression as OSGo.006, while the published reference title remains concept-first.
Elementary Overview
Imagine a shelf with four numbered spaces. An array is the shelf with its fixed number of spaces. A slice is a window showing some of those spaces. Two windows can show the same shelf, so changing an item through one window can change what the other window sees. A slice also remembers its current length and how much of the shelf it can reach before more storage is required. Go uses slices often because their length can grow as a program collects data.
Learning Objectives
- Declare arrays and slices and identify their different type syntax.
- Explain slice length, capacity, indexing, and shared backing storage.
- Use append and copy correctly while controlling accidental data sharing.
- Read a runnable example and verify behavior with unit tests.
- Recognize why capacity growth is not an API guarantee about underlying memory.
The Go Programming Language, “Arrays and Slices,” January 23, 2024. Official project video introducing the two sequence types and their behavior.
Fixed Arrays and Flexible Slices
The declaration [4]int specifies exactly four integers. In contrast, []int specifies a slice of integers without a fixed length in the type. Arrays are values: assigning an array to another variable copies its elements. A slice value contains information about its backing storage, length, and capacity. Assigning a slice copies the slice value, but not necessarily its elements. The official language specification describes array and slice types separately.
An array can be declared using values := [4]int{10, 20, 30, 40}. Selecting values[1:3] creates a slice containing elements at positions 1 and 2, excluding position 3. Go indexes sequences from zero, a convention shared by the earlier C arrays lesson. However, Go’s slices carry a length and capacity automatically, instead of requiring the caller to maintain a separate buffer length for ordinary slice operations.
The built-in len function reports how many slice elements are currently accessible. The built-in cap reports the maximum number of elements reachable from the slice’s starting position within its backing array, without reallocating. For a four-element array and a view values[1:3], the slice length is 2 and capacity is 3. Indexing at or beyond the current length panics even when the capacity is larger. That distinction prevents treating spare capacity as already initialized, addressable slice elements.

Shared Memory, Append, and Copy
The Go team’s explanation of append mechanics demonstrates why a growing slice must be assigned the return value of append. When capacity is sufficient, an append can reuse the existing backing array. When capacity is insufficient, Go allocates enough new storage and copies existing data. An application must never rely on an exact future capacity growth factor, because implementation choices may change. It should rely on slice contents and documented len/cap behavior instead.
Shared backing arrays are useful when a function intentionally edits an existing buffer. They can also create surprising side effects. A function receiving a slice can modify visible elements, but appending may redirect its local result to a different array. For independent data, use copy(destination, source) with a properly sized destination or clone the elements using append([]int(nil), source...). The built-in copy returns the number of elements actually copied, which is the smaller of the source and destination lengths.
freeCodeCamp.org, “Learn Go Programming,” June 20, 2019. Community course with arrays and slices beginning at approximately 1:47:53. The video is educational archive footage, not an official Go project demonstration.
Executable Example: Observe a Shared Backing Array
The following complete program uses a four-element array, takes a two-element view, modifies the view, extends it within available capacity, and finally makes an independent copy. Save the source as main.go. No third-party dependencies, external accounts, or network connections are required:
package main
import "fmt"
func main() {
slots := [4]int{10, 20, 30, 40}
window := slots[1:3]
fmt.Printf("array: %v\n", slots)
fmt.Printf("slice: %v len=%d cap=%d\n", window, len(window), cap(window))
window[0] = 99
extended := append(window, 50)
fmt.Printf("after shared edits: %v\n", slots)
fmt.Printf("extended: %v\n", extended)
independent := append([]int(nil), extended...)
independent[0] = 7
fmt.Printf("copy: %v original: %v\n", independent, slots)
dst := make([]int, len(window))
n := copy(dst, window)
fmt.Printf("copied %d values: %v\n", n, dst)
}
From the containing directory, initialize a small local module and run the example:
go mod init example.com/osgo006
go run .
The program was compiled and executed with Go 1.23.2 on Linux. Its observed standard output was:
array: [10 20 30 40]
slice: [20 30] len=2 cap=3
after shared edits: [10 99 30 50]
extended: [99 30 50]
copy: [7 30 50] original: [10 99 30 50]
copied 2 values: [99 30]
The first slice points at positions 1 and 2 of the original four-element array. Assigning 99 through the slice changes the array at position 1. Appending 50 extends the view into the last available slot, so the original array’s final element becomes 50. Creating a separate copy and assigning 7 changes only the copy. The original array retains 99. No runtime memory address is printed, and the example does not assume a particular allocation algorithm.
Unit Tests and Boundary Behavior
Automated tests are useful because slice bugs may only appear when a buffer has spare capacity or two variables unexpectedly share storage. Save the following source as main_test.go beside the program. It checks the slice length and capacity, shared writes, independently copied elements, and the number of copied values:
package main
import "testing"
func TestSliceAliasingAndCapacity(t *testing.T) {
a := [4]int{10, 20, 30, 40}
s := a[1:3]
if len(s) != 2 || cap(s) != 3 {
t.Fatalf("len=%d cap=%d", len(s), cap(s))
}
s[0] = 99
s = append(s, 50)
if a[1] != 99 || a[3] != 50 {
t.Fatalf("backing array not shared: %v", a)
}
}
func TestIndependentCopy(t *testing.T) {
original := []int{4, 5, 6}
copied := append([]int(nil), original...)
copied[0] = 100
if original[0] != 4 {
t.Fatalf("unexpected alias: %v", original)
}
}
func TestCopyCountsElements(t *testing.T) {
src := []int{3, 4, 5}
dst := make([]int, 2)
if n := copy(dst, src); n != 2 {
t.Fatalf("copied %d, expected 2", n)
}
if dst[0] != 3 || dst[1] != 4 {
t.Fatalf("copy mismatch: %v", dst)
}
}
Run go test -v . and go vet . in the module directory. In the local environment, all three named unit tests passed and go vet completed without diagnostics. The tests validate the illustrated cases only; they are not a proof that every future slice operation in an application is safe.
An out-of-range slice access causes a panic rather than exposing arbitrary memory. A nil slice has length and capacity zero and may still be appended to. A slice created using make([]int, 2, 5) has two accessible zero-valued elements and room for up to five before growing beyond that declared capacity. For functions handling untrusted input, check indices and sizes before operations, just as the Rust network parsing lesson does with safe slices and explicit errors.
Knowledge Check
- Why can changing a slice modify an array? Both views can use the same backing storage.
- Does capacity 5 permit indexing element 4 when length is 2? No; current index bounds are determined by length.
- Why save the result of append? A larger backing allocation may produce a new slice value.
- How can a function keep a private copy of integer elements? Allocate an appropriately sized slice and copy its contents.
Elementary Conclusion
Arrays are fixed-size storage, while slices are flexible views of storage. Length tells a program how much of a slice it can use immediately. Capacity tells it how much nearby storage can be reached before a larger allocation may be needed. When multiple slices share an array, they may see each other’s changes. Copying elements makes a separate collection when independence matters. Understanding the difference helps Go programs handle buffers without hidden data changes.
Official References
- A Tour of Go: Arrays and Slices.
- Go Slices: Usage and Internals, Go team.
- Arrays, Slices, and Strings: The Mechanics of Append, Go team.
- Go Language Specification, arrays, slices, length, capacity, append, and copy.
- Official Go Brand Guide, gopher illustration attribution.
Editor’s Note: The lesson advances the verified Go curriculum after OSGo.005. Three unit tests, the displayed sample output, and go vet were checked under go1.23.2 linux/amd64. The cover is original AI-generated colored-pencil editorial art of a fictional programmer, not documentary photography or an exact visualization of runtime memory. The Go Gopher image is authentic project artwork credited to Renée French. The official and community educational YouTube videos have verified source URLs; actual third-party player playback and mobile viewport screenshots were not independently tested.

For mobile scanning, display the QR on another device or use a supported saved-image scanner. Confirm the recipient 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and the 5,000-satoshi amount before sending.
We volunteer daily to ensure the credibility of information on BitcoinVersus.Tech is Verifiably True. If you would like to support our work and help further secure the integrity of our research initiatives, please scan the QR code above.
BitcoinVersus.Tech offers technical education for informational purposes. Readers should review official documentation and test code in their own environment before using it in production.

Leave a Reply