- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/unnecessary-blank-identifier
Language: Go
Severity: Info
Category: Best Practices
In Go, when using range iterations or receiving values from channels, it is recommended to avoid assigning the iteration or received value to the blank identifier _
. Instead, it is preferred to omit the assignment entirely.
Here’s why it is best to use for range s {}
, x = someMap[key]
, and <-ch
instead of using the blank identifier _
:
_
can introduce confusion and make it less clear what the purpose of the assignment is or if the value is discarded intentionally or accidentally._
as an assignment can unnecessarily pollute the variable space. Although Go allows the use of the blank identifier _
to disregard a value, it is a good practice to avoid introducing unnecessary variables, especially if they are never used.varName = _
as an indication of accidental assignment or failure to handle errors or returned values properly. Removing these assignments eliminates such warnings or false-positive detections.For example, consider the following code snippets:
for _ = range aSlice {}
x, _ = something()
_ = <- aChannel
for range aSlice {}
x = something()
<-aChannel
Both snippets achieve the same result, but the second one that omits the assignments using _
is preferred for its simplicity, readability, and adherence to Go’s best practices.
By using for range s {}
, x = someMap[key]
, and <-ch
instead of assigning to _
, you can write cleaner and more readable Go code while avoiding unnecessary variable assignments and potential confusion.
func main() {
for _ = range aSlice {
}
x, _ = myMap[key]
_ = <- aChannel
x, _ = myFunction()
for key, _ = range myMap {
}
for _, _ = range myMap {
}
}
func main() {
for aSlice {
}
x = myMap[key]
<- aChannel
for _, val = range mySlice {
}
}