- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/redundant-nil-check
Language: Go
Severity: Info
Category: Best Practices
In Go, it is recommended to avoid using something == nil && len(something) == 0
in an if
condition and instead use just len(something) == 0
.
Here are a few reasons why:
len(something) == 0
clearly conveys the intent of checking if a variable or collection is empty. It is more concise and easier to understand for other developers reading the code. Including something == nil
in the condition adds unnecessary complexity and may confuse readers.len()
function is specifically designed to handle different types, including slices, arrays, maps, and strings. Using len()
directly allows consistency in checking the length of any data structure without the need to handle specific cases for nil
.something == nil
adds an extra condition to handle the case when something
is nil
, which may or may not be desired or necessary. By focusing only on the length check with len(something) == 0
, you eliminate the need for a separate nil check, simplifying the code.Therefore, it is recommended to use len(something) == 0
to check if something is empty, rather than something == nil && len(something) == 0
. This approach enhances code readability, maintains consistency, and avoids unnecessary nil checks in Go.
func main() {
if something == nil && len(something) == 0{
println("foo")
}
}
func main() {
if len(something) == 0 {
println("foo")
}
}
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products