Fundamentals 17 min read

Mastering Go Slices: Creation, Manipulation, and Performance Tips

Go slices are dynamic, flexible data structures built on arrays, offering automatic growth, efficient memory use, and powerful operations such as creation via make or literals, slicing, appending, copying, iteration, and passing to functions, with detailed examples and visualizations illustrating their internal mechanics.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Go Slices: Creation, Manipulation, and Performance Tips

Slice is a special data structure in Go that wraps a dynamic array, providing automatic growth and shrinkage. The built‑in append() function expands a slice efficiently, while the underlying contiguous memory allows indexing, iteration, and GC optimization.

Internal implementation of slices

A slice is a small object that abstracts an underlying array and provides three fields: a pointer to the array, the length (number of accessible elements), and the capacity (maximum length before reallocation).

Creation and initialization of slices

Slices can be created in several ways. Knowing the required capacity influences the creation method.

Using make()

slice := make([]int, 5) // length and capacity 5
slice := make([]int, 3, 5) // length 3, capacity 5

Creating a slice with length greater than capacity causes a compile‑time error:

myNum := make([]int, 5, 3) // compile error: len larger than cap in make([]int)

Using literals

myStr := []string{"Jack", "Mark", "Nick"}
myNum := []int{10, 20, 30, 40}

Length and capacity can be set via indexed literals:

myStr := []string{99: ""} // length and capacity 100, element 99 empty

Array vs slice literals

myArray := [3]int{10, 20, 30}
mySlice := []int{10, 20, 30}

nil and empty slices

A nil slice is declared without initialization:

var myNum []int

Empty slices are created with make or literals:

myNum := make([]int, 0)
myNum := []int{}

Calling append(), len(), or cap() on nil or empty slices behaves the same.

Assigning values to slice elements

Elements are accessed and modified like arrays:

myNum := []int{10, 20, 30, 40, 50}
myNum[1] = 25

Creating new slices from slices

Slicing syntax:

slice[i:j]   // from i up to j (exclusive)
slice[i:j:k] // i start, j end, k capacity
slice[i:]   // i to end
slice[:j]   // start to j
slice[:]    // full copy

Example:

myNum := []int{10,20,30,40,50}
newNum := myNum[1:3] // length 2, capacity 4

Modifying one slice affects the other because they share the same array.

newNum[1] = 35 // also changes myNum[2]

Slices can only access elements within their length; out‑of‑range access panics.

newNum[3] = 45 // runtime panic: index out of range

Slice capacity limitation

The three‑index form can limit capacity:

fruit := []string{"Apple","Orange","Plum","Banana","Grape"}
myFruit := fruit[2:3:4] // length 1, capacity 2

Setting capacity beyond available range panics.

myFruit := fruit[2:3:6] // panic

Appending one slice to another

append

accepts a variadic list; using ... appends all elements of another slice:

num1 := []int{1,2}
num2 := []int{3,4}
fmt.Printf("%v
", append(num1, num2...)) // [1 2 3 4]

Iterating slices

Use range with for to get index and value copies:

myNum := []int{10,20,30,40,50}
for i, v := range myNum { fmt.Printf("index: %d value: %d
", i, v) }

Range creates a copy of each element; to modify in place use the index:

for i := range myNum { myNum[i] += 1 }

Copying between slices

The built‑in copy(dst, src) copies elements and returns the number copied:

num1 := []int{10,20,30}
num2 := make([]int,5)
count := copy(num2, num1) // count == 3
fmt.Println(num2) // [10 20 30 0 0]

Passing slices to functions

Slices are passed by value; the 24‑byte header (pointer, length, capacity) is copied, but the underlying array is shared.

myNum := make([]int, 1e6)
slice = foo(myNum)
func foo(s []int) []int { /* ... */ return s }

Summary

Slices are a distinctive Go data type that provide convenient collection handling and efficient passing between functions, making them widely used in Go code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GolangGoMemoryappendSlicecopy
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.