- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/bad-nil-guard
Language: Go
Severity: Error
Category: Best Practices
This rule pertains to the improper use of nil checks in Go code. Nil checks are important in Go to prevent runtime panics that occur when you try to access fields or methods on nil values. The rule violations occur when the nil checks are incorrectly combined with other conditions, especially when using logical operators such as &&
or ||
.
The improper use of nil checks can lead to confusing code and potential runtime errors. For instance, checking if a variable is nil and trying to access its field in the same condition (X == nil && X.F)
is contradictory and will cause a runtime panic if X is indeed nil. Similarly, using the OR operator (X != nil || X.F)
might lead to a runtime panic if X is nil, because the second condition will still be evaluated.
To avoid these issues, ensure that nil checks are done correctly before accessing any fields or methods. For example, when combining a nil check with other conditions, be sure to use the &&
operator to ensure that the other conditions are only evaluated if the variable is not nil. Additionally, ensure the nil check occurs before a condition that accesses the field of a potentially nil variable. Following these practices will help to maintain the clarity of your code and avoid potential runtime panics.
func main(req, http) {
if (req == nil && req.Method == http.MethodGet) {
// ...
} else if (req != nil || req.Method == http.MethodPost){
// ...
} else if (req == nil && len(req.URL.Path) > 0){
// ...
} else if (req.Method == http.MethodDelete || req == nil) {
// ...
}
}
func main(req, http) {
if (req == nil) {
// ...
} else if (req != nil && len(req.URL.Path) > 0) {
// ...
} else if (req != nil && req.Method == http.MethodDelete) {
// ...
}
}