CodeGym /コース /Go SELF /Nil slice vs empty slice: initialization and checks

Nil slice vs empty slice: initialization and checks

Go SELF
レベル 11, レッスン 3
使用可能

1. nil slice and empty slice: what is the difference

When you write a program in Go, you very quickly start storing data as a “list”: numbers, strings, input results, accumulated values in a loop. And almost immediately a situation arises: “the list is empty.” But empty in what sense? Does it not exist at all (not initialized), or does it exist, but has 0 elements?

In human language, that sounds like nitpicking. In programming language, it is sometimes an important distinction: it affects checks, what can be compared, and how your code is read by other people (including future you, who will look at this code a month later and think: “who wrote this?”).

Zero value for []T: what a nil slice means

In Go, almost every type has a default value (zero value). For int it is 0, for bool — false, for string — the empty string "". For a slice []T, the zero value is nil. That is, “there is no slice”: it does not point to any elements.

The most common form where you will see this is a regular variable declaration:

package main

import "fmt"

func main() {
	var nums []int

	fmt.Println(nums == nil)          // true
	fmt.Println(len(nums), cap(nums)) // 0 0
	fmt.Println(nums)                 // []
}

Pay attention to a small “trap for beginners”: printing fmt.Println(nums) shows []. At first glance, this looks like an “empty list”. But technically, it is a nil slice.

Remember three facts about a nil slice:

nums == nil        → true
len(nums)          → 0
cap(nums)          → 0

Why does this fit the “pointer + len + cap” model? Because the pointer = nil, and length and capacity are zero — “there is nowhere to look and nothing to see.”

2. Getting to know make

In Go there are two similar-looking words — new and make. At the start, it is easier to remember one thing: make is used to create ready-to-use containers. Primarily, these are slices, maps, and channels. Today we only need slices.

When you write:

tasks := make([]string, 0)

you are asking Go: “make me a slice of strings of length 0.” That is, there are no elements yet, but the slice object already exists and can be safely passed, returned from functions, and grown with append.

make for slices has two forms — and both read very literally:

make([]T, n)      // length n: elements already “exist” and are filled with zero value
make([]T, n, cap) // length n and capacity reserve cap (cap >= n)

For example, this is not an “empty list with 3 slots”, but a list of three elements, just zero-valued for now:

package main

import "fmt"

func main() {
	a := make([]int, 3)
	fmt.Println(a, len(a), cap(a)) // [0 0 0] 3 3
}

And this is exactly “still empty, but with room to grow”:

package main

import "fmt"

func main() {
	b := make([]int, 0, 3)
	fmt.Println(b, len(b), cap(b)) // [] 0 3
}

And one more thing: make is needed not because you “cannot do without it”, but because it lets you explicitly choose the slice form: create length n immediately for filling by index, or create an empty one with capacity if you will add elements gradually.

3. Empty slice: what it is and how to get it

An empty slice is a slice whose len == 0, but at the same time it is not equal to nil. That is, “there is a slice”, just with zero elements for now.

There are two most popular ways to get an empty slice:

Literal []T{}

This option is convenient when you want to show directly in code: “this is an empty collection, but still a collection.”

package main

import "fmt"

func main() {
	tasks := []string{}

	fmt.Println(tasks == nil)           // false
	fmt.Println(len(tasks), cap(tasks)) // 0 0
	fmt.Println(tasks)                  // []
}

make([]T, 0)

This is almost the same in meaning, but looks like “we are creating a slice programmatically.”

package main

import "fmt"

func main() {
	tasks := make([]string, 0)

	fmt.Println(tasks == nil)           // false
	fmt.Println(len(tasks), cap(tasks)) // 0 0
}

Technically, []string{} and make([]string, 0) usually produce the same picture: length 0, capacity 0, not nil. But in your head you can keep a simple association: literal — “empty value in code”, make — “container created”.

Cheat sheet: nil vs empty

When the differences start to blur together, it is better to stop for a minute and check a simple table. It saves a lot of time and nerves.

Slice state How to create s == nil len(s) cap(s) Printing fmt.Println(s)
nil slice
var s []int
true
0
0
[]
empty slice
s := []int{}
false
0
0
[]
empty with capacity reserve
s := make([]int, 0, 10)
false
0
10
[]

Pay special attention to the third row: len == 0, but cap can be large. This is a normal situation: “there are no elements yet, but space for growth has been prepared.”

4. Checks and initialization: len(s) == 0 and s == nil

Which checks are correct: len(s) == 0 or s == nil

When you check a slice, it is important to ask yourself honestly: what exactly do I want to know? And this is where the most common mistakes begin.

If you want to know “are there any elements”, then the correct question to the code sounds like this: is the length zero or not? That means the check should be done through len.

if len(tasks) == 0 {
	fmt.Println("There are no tasks yet") // There are no tasks yet
}

If you check tasks == nil, you are asking something else: “is the slice not initialized / absent as a value?” That can matter, but that is already about the meaning of the data, not about the presence of elements.

To feel the difference, let us look at an example where both checks produce different results:

package main

import "fmt"

func main() {
	var a []int  // nil
	b := []int{} // empty

	fmt.Println(len(a) == 0, a == nil) // true true
	fmt.Println(len(b) == 0, b == nil) // true false
}

And now the rule that usually makes a beginner’s code calmer:

  • If you need to “check whether the list is empty”, check len(s) == 0.
  • If you need to “check whether the slice is initialized”, check s == nil.

When s == nil really makes sense

Sometimes the difference between nil and empty is important, just not as often in the very first programs.

Imagine that you have a function that optionally collects data. If there is no data at all (for example, the user did not enable that option), you want to return exactly nil to show “the value is absent”. But if the user enabled the option, yet there are zero results — then return empty to show “the value exists, but it is empty”.

Let us model this without complicated topics:

package main

import "fmt"

func buildHints(enabled bool) []string {
	if !enabled {
		return nil // hints are disabled
	}
	return []string{} // enabled, but empty for now
}

func main() {
	a := buildHints(false)
	b := buildHints(true)

	fmt.Println(a == nil, len(a)) // true 0
	fmt.Println(b == nil, len(b)) // false 0
}

Here len is the same (0), but the meaning is different. And this is exactly the situation where == nil is useful: not for “emptiness”, but for “presence of a value”.

Careful initialization: what to choose in real code

When you start writing functions and passing slices between them, you develop a style. And it is better to shape it now, while the program is small.

If you build a list with append (more on that in the next lecture) and you have no requirements for preallocating memory, then var s []T is a completely normal start. It is short, readable, and does not force you to think about make too early.

If you want to show explicitly “this is definitely a collection, even if it is empty”, then s := []T{} is also a good option. It often appears when you return a value from a function and want to guarantee that the caller gets a non-nil value.

If you know in advance that you will add about N elements, and you do not want append to expand the internal buffer several times, then make([]T, 0, n) appears. But this is more about efficiency and predictability of growth, and in the context of today’s lecture what matters more to us is the meaning of nil vs empty, not optimizations.

5. What is safe to do with a nil slice

When people first see a nil slice, they often feel anxious: “If it is nil, then everything will crash right now.” The good news is that Go is quite friendly to nil slices. They can be used safely in many places.

len, cap, and range are safe

Since len(nilSlice) == 0, the loop simply will not run:

package main

import "fmt"

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

	sum := 0
	for _, v := range nums {
		sum += v
	}

	fmt.Println(sum) // 0
}

This is a very important practical point: because of it, a nil slice can often be kept as the “empty list by default”, without spawning extra ifs.

Indexing s[0] is NOT safe when len(s) == 0

This is the place where everyone crashes, including experienced developers, just less often. Indexing works only within the range 0..len(s)-1. So both nil and empty are equally dangerous for s[0] if the length is zero.

package main

import "fmt"

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

	if len(nums) > 0 {
		fmt.Println(nums[0])
	} else {
		fmt.Println("There is no first element") // There is no first element
	}
}

Why nil and empty look the same when printed

When fmt.Println prints a slice, it prints the “representation of elements”. If there are zero elements, then from the output perspective there is almost no difference: “there is nothing to print.”

But inside, the program distinguishes two states:

  • nil slice: “there is no underlying array, pointer is nil”
  • empty slice: “the underlying array may exist (or be optimized), but length is 0”

From the point of view of the slice model (pointer/len/cap), this means: for nil the pointer is “empty”, and for empty the pointer may be not nil, but the length is still 0. That is exactly why s == nil separates these cases, while len(s) == 0 does not.

If you want to “see” the difference in debugging, it is convenient to use Printf and print both len, cap, and the check against == nil:

package main

import "fmt"

func main() {
	var a []int
	b := []int{}
	c := make([]int, 0, 3)

	fmt.Printf("a: len=%d cap=%d nil=%v\n", len(a), cap(a), a == nil) // a: len=0 cap=0 nil=true
	fmt.Printf("b: len=%d cap=%d nil=%v\n", len(b), cap(b), b == nil) // b: len=0 cap=0 nil=false
	fmt.Printf("c: len=%d cap=%d nil=%v\n", len(c), cap(c), c == nil) // c: len=0 cap=3 nil=false
}

6. Example: a task list in a learning app

Now is the perfect moment to connect the topic to something “alive”, rather than abstract nums. Let us imagine that we are writing a very simple console program “TaskBox”: it reads tasks and prints them. Before slices, many people would try to store tasks in a fixed-size array, but now it is more logical to use []string.

The main goal of this section is to feel that a nil slice does not interfere with normal work if we make the checks correctly.

Printing a task list: the correct “empty” check

Now let us make a small function that prints tasks nicely. Important: it must work correctly for both nil and empty.

package main

import "fmt"

func printTasks(tasks []string) {
	if len(tasks) == 0 {
		fmt.Println("Task list is empty") // Task list is empty
		return
	}

	for i, t := range tasks {
		fmt.Printf("%d) %s\n", i+1, t)
	}
}

func main() {
	var tasks []string // nil
	printTasks(tasks)

	tasks = append(tasks, "Make lecture 53 understandable")	// add new text to the end of the slice
	printTasks(tasks)
}

The key point: we do not ask tasks == nil. We do not care why there are no tasks — because the list was not created or because it was created empty. We only care whether there are elements.

7. Typical mistakes: nil slice and empty slice

Mistake #1: checking “emptiness” via s == nil.
Such code works “sometimes” — exactly until someone creates s := []T{} or make([]T, 0). The slice will be empty, but not nil, and the check will break the logic. If you want to know whether there are elements, ask that question directly: len(s) == 0.

Mistake #2: thinking that fmt.Println(s) shows the difference between nil and empty.
Both variants are most often printed as [], and visually it seems like the same thing. If the difference matters, print s == nil and len/cap via Printf, otherwise you will be debugging “by the shadow on the wall”.

Mistake #3: indexing without checking length.
It is very tempting to write first := s[0] and think, “well, I have a list.” But nil and empty both fail on s[0], if len(s) == 0. Reliable pattern: first if len(s) == 0 { ... }, then indexing.

Mistake #4: overcomplicating code with nil checks where len is enough.
Beginners sometimes write if s != nil && len(s) > 0 { ... }. The second part (len(s) > 0) already guarantees that there are elements in the slice. An extra check for nil does not make the code safer, but it does make it longer and less readable. In Go, the most direct question to the data often wins: “how many elements are there?”.

1
タスク
Go SELF, レベル 11, レッスン 3
ロック未解除
3つのプロファイル
3つのプロファイル
1
タスク
Go SELF, レベル 11, レッスン 3
ロック未解除
空モード
空モード
1
タスク
Go SELF, レベル 11, レッスン 3
ロック未解除
nil の正規化
nil の正規化
1
タスク
Go SELF, レベル 11, レッスン 3
ロック未解除
最初の要素
最初の要素
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION