CodeGym /행동 /Go SELF /clear: why zero out the tail after deletion

clear: why zero out the tail after deletion

Go SELF
레벨 13, 레슨 2
사용 가능

1. What clear does and why it is needed

If you have only just gotten used to append, copy, and s[a:b], then clear may first look like "just another magical nail" in Go's toolbox. But in fact clear solves a very practical pain point: we know how to reduce len (make s = s[:newLen]), but that does not erase values from the backing array. In other words, we can "hide" elements from view, but they are still there — like forgotten pizza in the fridge: you do not see it, but the smell will remind you a day later.

clear is a built-in function. For a slice, it writes the zero value into the elements of the range. It is important to state this right away: clear does not change len or cap. It does not "cut anything off"; it simply "wipes the floor."

This philosophy is very typical of Go: the language often added small built-in mechanisms that removed repetitive boilerplate code and made behavior more predictable. Historically, a similar story happened with append: people used to write manual "addToList" functions with make + copy, and then that was packaged into one clear tool.

Mini-example: clear does not make a slice empty

package main

import "fmt"

func main() {
	s := []int{10, 20, 30}
	clear(s)

	fmt.Println(s)      // [0 0 0]
	fmt.Println(len(s)) // 3
}

2. Zero value and clearing references

Now comes the moment where Go behaves like a strict math teacher: "do not imagine things, memorize the definitions." clear writes the zero value for the element type.

For int this is 0, for bool this is false, for string this is "". For "reference" types (for example, []int, map[string]int) the zero value usually looks like nil. And this is critical: when you zero out a reference type element, you remove the reference to the data. And that is no longer about "pretty output", but about memory and the garbage collector (GC).

We are not diving deep into GC yet. A very practical model is enough:

If somewhere in the program a reference to data remains, GC considers that data still needed and does not free the memory.

clear is one way to neatly remove such references when you have logically "deleted" an element from a collection.

Table: clear for different types

Element type T Zero value after clear What this means in practice
int
0
"Erased the number" (no effect on memory beyond the cell itself)
bool
false
"Erased the flag"
string
""
Removed the reference to string data (important for memory)
[]int
nil
Removed the reference to another slice's backing array
map[string]int
nil
Removed the reference to the hash table

We are not going into map in depth right now; just note that clear is not "only for []T".

Mini-example: clear clears part of a range

package main

import "fmt"

func main() {
	s := []string{"A", "B", "C", "D"}
	clear(s[1:3])
	fmt.Println(s) // [A  D]
	// to be precise: ["A" "" "" "D"]
}

3. Why reducing len does not erase the tail

Now we are approaching the main reason why people often use clear after deletion. This is where one of the most common "ghost bugs" with slices lives.

A slice has len and cap. len says which part of the backing array is currently visible. cap says how far the backing array extends from the start of that slice.

What lies beyond len, but inside cap, is usually called the "tail." It is not visible through ordinary indexing s[i], because indexes are checked against len. But the tail really exists in backing-array memory.

Here is a mental picture:

backing array:  [ A ][ B ][ C ][ D ][ ? ][ ? ]
slice s:        ^----------------^
                len=4            cap=6

tail:                         [ ? ][ ? ]  (this is part of the backing array, but beyond len)

And now an important trick: if you did s = s[:2], the backing array did not "shrink" and did not "erase" itself. You simply changed the "view window."

Mini-example: the tail can be seen when extending a slice

This example looks a bit artificial (because s[:cap(s)] is rarely written in real code), but it shows the mechanics very well.

package main

import "fmt"

func main() {
	s := []string{"A", "B", "C", "D"}
	s = s[:2] // we only see A and B

	t := s[:cap(s)] // expanded visibility to cap
	fmt.Println(t)  // [A B C D]
}

Moral: "deleting" an element by reducing len is not the same as "erasing" the value in the backing array.

By the way, in earlier topics you already encountered the cap control tool via the full slice expression s[a:b:c]. It was added precisely to manage access to the backing array and tail more safely.

4. Why clean the tail: bugs and memory

It is easy to say: "Well, the tail is there, so what?" But there are two reasons why you should clear the tail after deletion — and both regularly bite in practice.

The first problem is logical. After deletion, you often expect that what was removed no longer exists anywhere else. But if somewhere by mistake a reslice happens (or you pass a sub-slice with a large cap and someone does append), the old value can unexpectedly resurface. This is not magic; it is simply that same tail you did not wipe.

The second problem is memory. It is especially important when slice elements hold references to large data: strings, other slices, maps. If you "deleted" an element but the reference to it still remains in the tail of the backing array, GC will continue to consider that data needed, and memory may not be released. As a result, your code logically "removed" the data, but in terms of memory — "not quite."

You can think of it like this: reducing len means "we no longer use it", while clear means "and there are no more references either."

5. Removing an element: copy + clear + new len

Now we arrive at the main practical conclusion: after deletion, especially stable deletion where we shift the tail left with copy, a duplicate remains at the end. This "last element of the old length" is logically no longer needed, but physically the old value will still be there.

The typical pattern therefore looks like this:

  1. Shifted elements left (copy).
  2. Zeroed out the last element of the old length (clear over a range of one element).
  3. Shortened len (s = s[:len(s)-1]).

Mini-example: stable remove of one element

package main

import "fmt"

func removeAtStable(s []string, i int) []string {
	if i < 0 || i >= len(s) {
		return s
	}

	copy(s[i:], s[i+1:])           // shift the tail left
	clear(s[len(s)-1 : len(s)])    // zero out the last slot
	return s[:len(s)-1]            // reduce len
}

func main() {
	tasks := []string{"eat", "sleep", "code", "repeat"}
	tasks = removeAtStable(tasks, 1)

	fmt.Println(tasks) // [eat code repeat]
}

Notice clear(s[len(s)-1 : len(s)]): this is a range of length 1. Yes, it looks a bit "bureaucratic", but it is very explicit: "we are clearing exactly one element."

If you want it shorter (and you are sure you understand the boundaries), you can write clear(s[len(s)-1:]), but that is a different idea: "clear the tail up to cap." For our current situation, more often you want to clear exactly that "freed slot."

6. Removing a range: clear s[newLen:oldLen]

Deleting a range [i:j) is the same thing, only with a wider "hole." We close it with the tail via copy(s[i:], s[j:]). After that, several "extra" elements remain at the end (exactly j-i of them) — and those are precisely what should be cleared.

Here it is convenient to think in terms of two lengths: the old oldLen and the new newLen. While you have not shortened len yet, the range for clear is easy to state explicitly.

Mini-example: delete range + clear the tail

package main

import "fmt"

func deleteRange(s []string, i, j int) []string {
	if i < 0 {
		i = 0
	}
	if j > len(s) {
		j = len(s)
	}
	if i >= j {
		return s
	}

	oldLen := len(s)
	moved := copy(s[i:], s[j:]) // how much actually moved
	newLen := i + moved

	clear(s[newLen:oldLen]) // clear exactly the "freed" part
	return s[:newLen]
}

func main() {
	s := []string{"A", "B", "C", "D", "E", "F"}
	s = deleteRange(s, 2, 5)

	fmt.Println(s) // [A B F]
}

The important thing here is that clear is done before s = s[:newLen] (or while preserving oldLen). Otherwise you lose convenient access to the "old tail" range.

7. Example: a mini task manager

Let us continue our mini application line. Suppose we have the simplest task manager: the task list is stored as []string. We can print tasks, add them, and delete by index.

Now we will add deletion so that it does not leave "dangling" references in the backing-array tail.

Step 1: print tasks

package main

import "fmt"

func printTasks(tasks []string) {
	for i, t := range tasks {
		fmt.Printf("%d) %s\n", i, t)
	}
}

func main() {
	tasks := []string{"read", "write", "delete tail carefully"}
	printTasks(tasks)
	// 0) read
	// 1) write
	// 2) delete tail carefully
}

Step 2: delete by index with clear

package main

import "fmt"

func removeTask(tasks []string, i int) []string {
	if i < 0 || i >= len(tasks) {
		return tasks
	}

	copy(tasks[i:], tasks[i+1:])
	clear(tasks[len(tasks)-1 : len(tasks)])
	return tasks[:len(tasks)-1]
}

func main() {
	tasks := []string{"read", "write", "sleep", "repeat"}
	tasks = removeTask(tasks, 2)

	fmt.Println(tasks) // [read write repeat]
}

What is nice here is that the function returns a new slice. This directly matches the "length rule": if an operation changes len, the caller must receive the updated slice. Otherwise you are almost guaranteed to end up in a strange state where "it changed inside, but not outside."

Process diagram for deletion and cleanup

Sometimes it is easier for the brain to see once than to read five times. Here is a flowchart for the "stable remove + clear tail" process:

flowchart TD
    A[There is a slice tasks, len=n] --> B["Shift the tail: copy(tasks[i:], tasks[i+1:])"]
    B --> C[A duplicate of the last element appears at the end]
    C --> D["Clear the last slot: clear(tasks[n-1:n])"]
    D --> E["Shorten len: tasks = tasks[:n-1]"]
    E --> F[Done: order preserved, tail holds no references]

8. Typical mistakes when using clear after deletion

Mistake #1: expecting clear to change the length.
A very common logical trap: you do clear(s) and expect that "the slice became empty." But clear has nothing to do with size. It is about values. If you want an empty-by-length slice, that is s = s[:0]. If you want empty values but the same length, that is exactly clear(s).

Mistake #2: clearing the wrong range because of [a:b) boundaries.
When you clear the tail, it is almost always about a half-open interval. For example, the last element of the old length is [oldLen-1 : oldLen], not [oldLen-1 : oldLen-1] (that is empty) and not [oldLen : oldLen+1] (panic). The safest approach at first is to preserve oldLen and write ranges explicitly, even if it looks a bit longer.

Mistake #3: forgetting that deletion is at least two actions, and clear is separate.
Sometimes people write copy(s[i:], s[i+1:]) and think they have "deleted" the element. But the length is still the old one, and the last element will repeat. Then they add s = s[:len(s)-1] and consider the task done. For []int this is often "fine", but for []string or [][]byte you quietly leave references in the tail. If your code reduced len, it is useful to ask yourself: "Does the tail need wiping?"

Mistake #4: doing clear after you have lost access to the tail.
If you first did s = s[:newLen] and did not save the old length anywhere, then clearing the "freed part" via clear(s[newLen:oldLen]) is no longer possible — you do not have oldLen. Yes, you can clear up to cap, but that is a different solution and not always what you wanted. In deleting functions, it is often easier to save oldLen first, then clear, and only then change len.

Mistake #5: ignoring memory retention as if it were a myth.
When the data is small, you will not see the problem. When the slice holds large strings or large sub-slices, "deleted but not cleared tail" turns into a memory leak "by feeling": memory does not come back, the process grows, and you get sad and suspect Go of all mortal sins. Usually Go is not at fault, but that very tail you were too lazy to zero out.

1
과제
Go SELF, 레벨 13, 레슨 2
잠금
구간 지우기
구간 지우기
1
과제
Go SELF, 레벨 13, 레슨 2
잠금
마지막 항목 제거
마지막 항목 제거
1
과제
Go SELF, 레벨 13, 레슨 2
잠금
안정적으로 삭제하기
안정적으로 삭제하기
1
과제
Go SELF, 레벨 13, 레슨 2
잠금
범위 삭제
범위 삭제
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION