ADVERTISEMENT
ADVERTISEMENT

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


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.