How to check array is empty in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, we are going to learn how to check an empty array in golang, here we will use the len() method to verify array is empty or not.

The len() method is used to get the length of an array also it means a number of elements and when we know the count of elements we can quickly check if it’s empty or not by comparing to zero.

Let’s understand with an example…

Here, we will create two arrays the first array has some elements, and the second is empty.

we will check the length of both arrays and print which array is empty in the golang console.

Note: In golang slice is an array.

package main

import (

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!")

When you run the above program you will get an output, in which the array is empty.

let’s check the output.


Try it yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us


Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts