Fundamentals 8 min read

Master Go Slices: Understanding make, append, copy, and Capacity

This article explains Go slice fundamentals, covering how to create slices with make, the relationship between length and capacity, the behavior of append, why zero values appear, the automatic growth mechanism, and how to safely copy slices using the copy function, illustrated with code examples and diagrams.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Go Slices: Understanding make, append, copy, and Capacity

Continuation of Go Basics: Slices Supplement

Hey, I'm 星期八, continuing the Go basics series with a deep dive into slices.

make Mystery

We can create a slice using make : var names = make([]string, 10, 10) This creates a slice with length 10 and capacity 10.

Do you have questions?

What are length and capacity? What is their relationship?

Slice Essence

A slice is essentially a view over an underlying array; Go wraps an array to provide convenient operations such as add, delete, update, and query.

Example:

package main

import "fmt"

func main() {
    var names = make([]int, 4, 10) // default int value is 0
    fmt.Println(names, len(names), cap(names)) // result: [0 0 0 0] 4 10
}

The underlying array can automatically expand when its capacity is exceeded.

Note: In Go, it is recommended to create slices with make and consider capacity to avoid unnecessary automatic expansions.

Why does append leave leading zeros?

When we create a slice with make([]int, 5, 10), the first five elements are the zero value of int (0). Appending adds elements after those zeros until the capacity is reached, then triggers growth.

var names = make([]int, 5, 10)
names = append(names, 11, 23, 231)
fmt.Println(names) // [0 0 0 0 0 11 23 231]

To start without leading zeros, set the length parameter to 0:

var names = make([]int, 0, 10) // result: [11 23 231]

Why not use var []type to create a slice?

Declaring var names []int creates a nil slice with length and capacity 0. When we append, a new underlying array is allocated, changing the slice’s address, length, and capacity.

var names []int
fmt.Printf("addr:%p len:%d cap:%d
", names, len(names), cap(names))
names = append(names, 1, 2, 3)
fmt.Printf("addr:%p len:%d cap:%d
", names, len(names), cap(names))

Copying Slices

Assigning one slice to another copies only the slice header, so both variables reference the same underlying array. Modifying one affects the other.

var names1 = make([]string, 0, 10)
names1 = append(names1, "张三")
names1 = append(names1, "李四")
var names2 = names1
fmt.Println(names1, names2) // [张三 李四] [张三 李四]
names1[0] = "张三666"
fmt.Println(names1, names2) // [张三666 李四] [张三666 李四]

To avoid this, use copy to duplicate the data:

var names2 = make([]string, 2, 10)
copy(names2, names1)

Automatic Growth Mechanism

Go automatically expands a slice’s capacity when needed, allocating a larger underlying array and copying existing elements.

Summary

We have covered Go slice fundamentals, including creation with make , length vs. capacity, append behavior, and safe copying with copy . Feel free to leave questions in the discussion area.

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.

GoappendslicescapacitycopyMake
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.