How to Check if Slice Is Empty Golang

1. Introduction

In Go, checking whether a slice is empty is a common task that you might need to perform. An empty slice is a slice that has no elements, which means its length is 0. This blog post will explain how to check if a slice is empty in Go.

Definition

A slice in Go is considered empty if it has a length of 0. It is important to note that an empty slice is not the same as a nil slice. An empty slice has been initialized but does not contain any elements, while a nil slice has not been initialized at all.

2. Program Steps

1. Define an empty slice and a nil slice.

2. Write a function that checks if a slice is empty.

3. Call the function with different slices to demonstrate its usage.

3. Code Program

package main

import "fmt"

// isEmpty checks if the provided slice of ints is empty
func isEmpty(s []int) bool {
	return len(s) == 0
}

func main() {
	// Step 1: Define an empty and a nil slice
	var nilSlice []int
	emptySlice := make([]int, 0)

	// Step 2: Call the isEmpty function with the nil slice
	fmt.Println("Is nil slice empty?", isEmpty(nilSlice))

	// Step 3: Call the isEmpty function with the empty slice
	fmt.Println("Is the initialized but empty slice empty?", isEmpty(emptySlice))
}

Output:

Is nil slice empty? true
Is the initialized but empty slice empty? true

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for output operations.

3. isEmpty function - Takes a slice of integers as a parameter and returns true if the length of the slice is 0.

4. nilSlice is declared but not initialized, which means it is nil.

5. emptySlice is initialized with make, specifying a length of 0, making it an empty slice.

6. The isEmpty function is called with both nilSlice and emptySlice to check if they are empty.

7. The fmt.Println function is used to print the result of the checks to the console.

8. The output confirms that both the nil and the initialized but empty slice are considered empty by the isEmpty function.


Comments