Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for an empty slice?

Tags:

slice

go

I am calling a function that returns an empty array if there are no values.

When I do this it doesn't work:

if r == [] {     fmt.Println("No return value")             } 

The work around I'm using is:

var a [0]int if r == a {     fmt.Println("No return value")             } 

But declaring a variable just to check the return value doesn't seem right. What's the better way to do this?

like image 284
Kshitiz Sharma Avatar asked Jul 01 '16 11:07

Kshitiz Sharma


People also ask

What defines an empty slice?

An empty slice has a reference to an empty array. It has zero length and capacity and points to a zero-length underlying array.

How do you declare an empty slice?

Empty slice can be generated by using Short Variable Declarations eg. foo := []string{} or make function.

Is empty slice nil?

To tell if a slice is empty, simply compare its length to 0 : len(s) == 0 . It doesn't matter if it's the nil slice or a non- nil slice, it also doesn't matter if it has a positive capacity; if it has no elements, it's empty.

Can a slice be nil?

The zero value of a slice is nil . A nil slice has a length and capacity of 0 and has no underlying array.


1 Answers

len() returns the number of elements in a slice or array.

Assuming whatever() is the function you invoke, you can do something like:

r := whatever() if len(r) > 0 {   // do what you want } 

or if you don't need the items

if len(whatever()) > 0 {   // do what you want } 
like image 128
Simone Carletti Avatar answered Oct 06 '22 14:10

Simone Carletti