Home  >  Article  >  Backend Development  >  Does not rely on len() to check whether the initialized slice is empty

Does not rely on len() to check whether the initialized slice is empty

王林
王林forward
2024-02-12 18:10:06470browse

不依赖 len() 检查初始化切片是否为空

Question content

I have a use case where the built-in len() function is not suitable for checking if the initialized (non-zero) slice is empty.

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

I try to index the first element, however, if it doesn't exist, my program panics.

Workaround

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

The above is the detailed content of Does not rely on len() to check whether the initialized slice is empty. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete