Search code examples
gotime-complexityslice

Check If Initialized Slice Is Empty Without Relying On len()


I have a use case where builtin len() function isn't appropriate to check if an initialized (non-nil) slice is empty or not.

How can I safely check if a slice is empty without len()?

I tried to index the first element, however, if it does not exist it would panic my program.


Solution

  • How can I safely check if a slice is empty without len()?

    There is absolutely no reason to not use len(), so just use len as len is a O(1) operation.