×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

What is the easiest way to check if a slice is empty in Golang?

Here, we are going to learn the easiest way to check if a slice is empty in Golang? We are going to write a Golang program to check whether a given slice is an empty slice or not?
Submitted by IncludeHelp, on October 06, 2021

The easiest way to check if a slice is empty – to check the length of the slice, if it's 0 then the slice is empty. To get the length of a slice, we use the len() function which is an inbuilt function.

Consider the below example,

package main

import (
	"fmt"
)

func main() {
	s1 := []int{}
	s2 := []int{10, 20, 30, 40, 50}

	fmt.Println("s1:", s1)
	fmt.Println("s2:", s2)

	if len(s1) == 0 {
		fmt.Println("s1 is empty!")

	} else {
		fmt.Println("s1 is not empty!")
	}

	if len(s2) == 0 {
		fmt.Println("s2 is empty!")

	} else {
		fmt.Println("s2 is not empty!")
	}
}

Output:

s1: []
s2: [10 20 30 40 50]
s1 is empty!
s2 is not empty!

Golang FAQ »

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.