CodeGym /행동 /Go SELF /Slice growth and reallocation: append

Slice growth and reallocation: append

Go SELF
레벨 11, 레슨 4
사용 가능

1. Getting to know append

Up to now, we worked with slices as if they were a “shelf with slots”: there is s[0], s[1], and you can iterate over them in a loop. But at some point, a different kind of task inevitably appears: “count numbers down to zero,” “collect all words from input,” “read an unknown number of values.” And then one unpleasant thing becomes clear: you do not know the length of the list in advance.

In languages with “lists,” this usually looks like magic: you add an element — and the list grows by itself. In Go, there is no magic, but there is a very clear contract. A slice is not a container “on its own,” but a small description: how many elements exist now (len) and how much space is reserved for the future (cap). So “write the next element” is not just assignment by index. Sometimes there is enough space, sometimes there is not, and then you need a careful “move” into a larger piece of memory.

The append function is like a command: “add to the end, and if there is not enough room — expand the storage and return the updated slice to me.” That is why the first important habit in this lecture sounds almost like a traffic rule: you must always save the result of append. Not because Go is mean, but because after adding an element, your list may change in length, and sometimes even in the “address where the elements live.”

If you remember this idea, everything else about append becomes calm and predictable: len is about what “exists,” cap is about the “reserve space,” and append is about safe growth.

2. The append contract and why the result must be saved

Imagine that a slice is not a “rubber list,” but a label on a box: the label tells you how many elements are inside now (len) and how much room is still left in the box (cap). When you call append, you ask Go to “add one more element to the end.” Sometimes Go really puts it into the same box. And sometimes the box turns out to be too small, so Go takes a larger box, moves everything into it, and places the new element there.

This is where the main rule comes from: append always returns the updated slice. Even if the elements “look” like they stayed in the same place, after the addition len definitely changed. And if there was a “move,” then the reference to the data changed too. That is why code like append(s, x) without assignment is almost always a thinking error: it is as if you asked to “add something,” got a new label… and threw it in the trash.

The most correct basic pattern looks like this: “added it — saved the result.”

package main

import "fmt"

func main() {
	s := []int{1, 2}
	s = append(s, 3)
	fmt.Println(s) // [1 2 3]
}

Historical fact: before append appeared, people had to write code manually that checked cap, allocated a new array, copied the data, and only then added the element. This was such a common pain point that append appeared as a built-in function and made life noticeably easier.

The main rule of append: it returns a new slice

append looks like a normal function, but it is a built-in language function. And the key point is: the result of append is a slice that you must use further. Even if it seems like “it added to the end,” in reality it could have:

  1. written into the existing backing array (if cap was enough);
  2. allocated a new backing array, copied the elements there, and then written the new data there (if cap was not enough).

And in both cases append returns an updated slice header. There is solid logic in this: if append changed the length, it must give you the new len. If append did a reallocation, it must give you a new reference to the data. That is why in Go many functions that change the “shape” of a slice return the slice back (and this cannot be ignored).

From now on, treat this as a reflex: s = append(s, ...).

Note: this is not “Go being picky,” it is literally the function contract.

Why you cannot write append(s, x) and hope that “it will do”

When you write append(s, x) and do not save the result, you throw away the information about the new len on the floor (and possibly the new memory). From the program's point of view, the variable s remains the same: it has the same len, the same cap, and the same reference to the backing array.

An example of “making it look like you added an element, but in fact you did not”:

package main

import "fmt"

func main() {
	s := []int{1, 2}

	append(s, 3)                 // result ignored
	fmt.Println(s, len(s))       // [1 2] 2
	fmt.Println(append(s, 3))    // [1 2 3]  <-- but this is a temporary value
}

Here the last line prints a slice that exists, but it is not assigned to s. In other words, it is as if you bought bread, put it in a bag... and left the bag at the checkout.

A slightly more dangerous version is when you ignore the result inside a function:

package main

import "fmt"

func addOne(s []int) {
	append(s, 999) // result ignored
}

func main() {
	s := []int{1, 2}
	addOne(s)

	fmt.Println(s) // [1 2]
}

The slice in the parameter s is a copy of the slice header (a copy of the description). If you do not return the new slice from inside the function, the calling code will have no way to know that the length was supposed to change.

The correct version is to return the slice:

package main

import "fmt"

func addOne(s []int) []int {
	s = append(s, 999)
	return s
}

func main() {
	s := []int{1, 2}
	s = addOne(s)

	fmt.Println(s) // [1 2 999]
}

3. Slice growth and reallocation

len always grows, cap only sometimes (and in jumps)

When you add elements, len grows in a strictly predictable way: added one — length +1. Added three — length +3. But cap is trickier: Go tries to allocate memory so that future append calls are cheaper, so capacity often grows in “jumps.” How exactly it grows is an implementation detail, and you should not build logic around it. But it is useful to observe it so your brain stops expecting magic.

Let's write a tiny “growth sensor”:

package main

import "fmt"

func main() {
	s := make([]int, 0) // just an empty slice for now

	for i := 1; i <= 8; i++ {
		s = append(s, i)
		fmt.Printf("i=%d len=%d cap=%d s=%v\n", i, len(s), cap(s), s)
	}
}

The output will be roughly like this (the exact cap values may differ, and that is normal):

i=1 len=1 cap=1 s=[1]
i=2 len=2 cap=2 s=[1 2]
i=3 len=3 cap=4 s=[1 2 3]
...

What matters here are two ideas. First: len is “how many elements really exist,” and it is what indexing depends on. Second: cap is “how much space is allocated,” and it may change when Go decides it is time to expand.

Backing array reallocation: what happens during a “move”

The word “reallocation” sounds like something from accounting, but the meaning is simple: if there is not enough space, Go allocates a new larger array and copies your elements there. A very everyday analogy: you live in an apartment (backing array). As long as there are few things, it is fine. When there are more things than storage space (cap), you move to a larger apartment. The old address remains, but you are no longer there.

Inside append, the logic is roughly like this (simplified, not as a specification, but as a mental model):

flowchart TD
    A["There is a slice s (len, cap)"] --> B{"Is cap enough for the addition?"}
    B -->|yes| C["Write new elements into the same backing array, len increases"]
    B -->|no| D["Allocate a new larger backing array"]
    D --> E["Copy the old elements"]
    E --> F["Add the new elements"]
    C --> G["Return a new slice header"]
    F --> G

Now for the important consequence: if somewhere else you have another slice that referred to the old backing array, after reallocation it may become a “handle to the old place.”

Let's show this with an example. We will deliberately create a slice with a small cap to force Go to expand:

package main

import "fmt"

func main() {
	s := make([]int, 0, 1) // len=0, cap=1

	s = append(s, 1)
	t := s // t looks at the same place as s

	fmt.Printf("before: s=%v t=%v\n", s, t) // before: s=[1] t=[1]

	s = append(s, 2) // cap was 1, now 2 is needed => reallocation will happen
	t[0] = 99        // change the "old place"

	fmt.Printf("after:  s=%v t=%v\n", s, t) // after:  s=[1 2] t=[99]
}

The point of this demonstration is that after expansion s may have moved to a new backing array, while t remained pointing to the old one. So changing t[0] does not have to be reflected in s[0].

This is not a “Go bug”; it is a consequence of the slice being a small description structure. We already discussed that the assignment t := s copies the slice header. So after reallocation, these two headers start looking at different arrays.

append and a nil slice: a perfectly normal pair

Sometimes a beginner thinks: “If a slice is nil, then nothing can be added to it.” In practice, in Go a nil slice is a valid initial state for accumulating data. append knows how to start from nil: it simply allocates a backing array by itself.

package main

import "fmt"

func main() {
	var s []int // nil

	s = append(s, 10)
	s = append(s, 20)

	fmt.Println(s, s == nil) // [10 20] false
}

This is a very convenient style: “while there are no elements — just nil, and then we grow.” Also, ranging over a nil slice is safe, so you do not have to initialize something immediately just for peace of mind.

Micro-diagnostics: the address of the first element

Sometimes, to believe in the “move,” you want to see it with your own eyes. We can carefully print the address of the first element using "%p". Important: taking &s[0] is only possible when len(s) > 0, otherwise there will be a panic (because there is no element).

package main

import "fmt"

func main() {
	s := make([]int, 0, 1)

	s = append(s, 1)
	fmt.Printf("len=%d cap=%d addr=%p\n", len(s), cap(s), &s[0]) // addr=0x...

	s = append(s, 2) // reallocation is almost guaranteed
	fmt.Printf("len=%d cap=%d addr=%p\n", len(s), cap(s), &s[0]) // addr=0x... (most likely different)
}

If the address changed, then the backing array definitely moved. If by chance in some environment the address matches (rare, but theoretically you may encounter surprises due to optimizations/allocator behavior), do not draw a “scientific conclusion” from that: application logic must not depend on addresses; what matters to us is the model and the append contract, not the mystical “exactly where in memory the array lives.”

4. Practice: a mini task-list application

Earlier in the course, we worked a lot with individual variables and strings. Now we get a new superpower: storing many values of the same type. Let's start building the simplest task list (for now without files, without structs, without statuses — just strings in a slice). This app will be intentionally simple, but it will reinforce the idea that “append returns the updated slice.”

First, let's create memory for tasks and add a couple of items:

package main

import "fmt"

func main() {
	var tasks []string // nil slice, a normal start

	tasks = append(tasks, "Buy milk")
	tasks = append(tasks, "Learn append (and don't forget to save the result)")

	fmt.Println(tasks) // [Buy milk Learn append (and don't forget to save the result)]
}

Now let's add a function that adds a task correctly. Notice: the function returns the new tasks.

package main

import "fmt"

func addTask(tasks []string, title string) []string {
	tasks = append(tasks, title)
	return tasks
}

func main() {
	var tasks []string

	tasks = addTask(tasks, "Do morning exercises")
	tasks = addTask(tasks, "Pet the cat (the cat won't pet itself)")

	fmt.Println(tasks) // [Do morning exercises Pet the cat (the cat won't pet itself)]
}

And now let's deliberately show a typical mistake — a function that “does something,” but does not pass the result outward:

package main

import "fmt"

func addTaskWrong(tasks []string, title string) {
	append(tasks, title) // result thrown away
}

func main() {
	var tasks []string

	addTaskWrong(tasks, "This task will be lost")
	fmt.Println(tasks) // []
}

This kind of error is especially sneaky because the code compiles and looks logical, but the application behaves as if it “forgets sometimes.”

5. Typical mistakes when working with append

Mistake #1: ignore the return value of append.
The most common problem is to write append(s, x) and expect s to “update itself.” In Go, append returns a new slice because len, cap, and even the reference to the backing array may have changed. The habit of “always assigning the result” is not style, it is correctness.

Mistake #2: accidentally use := instead of = and “lose” the updated slice.
When a variable already exists, but inside a block you write s := append(s, x), you may create a new variable s that lives only in that block. Outside, the old one remains. It looks almost the same, but the effect is like a magic trick: “added it, but nothing was added.”

Mistake #3: thinking that two slices after t := s will forever share the same elements.
Before the first serious growth, this is often true, so the bug appears “not always.” But during reallocation, one slice may move while the other stays on the old backing array. As a result, changes through one stop being visible in the other — and that is normal behavior.

Mistake #4: trying to index “up to cap” instead of “up to len.”
Sometimes a person sees cap=10 and thinks: “Well, then I have 10 cells.” There may be room, but there are no logical elements yet: indexing is allowed only in the range 0…len-1. If len=0, then s[0] is a panic, even if cap is huge.

Mistake #5: mixing the “fill by index” style and the “grow with append” style without understanding the length.
For example, create make([]int, 5) (that is, len=5, already five zeros), and then also call append in a loop. As a result, you will get “five zeros, and then useful elements” — and you will keep wondering who slipped you those zeros. The problem is not append; the problem is that you started with the wrong len.

1
과제
Go SELF, 레벨 11, 레슨 4
잠금
센서 스트림
센서 스트림
1
과제
Go SELF, 레벨 11, 레슨 4
잠금
패킷 업데이트
패킷 업데이트
1
과제
Go SELF, 레벨 11, 레슨 4
잠금
잃어버린 append
잃어버린 append
1
과제
Go SELF, 레벨 11, 레슨 4
잠금
분리된 슬라이스
분리된 슬라이스
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION