- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/switch-default-first-or-last
Language: Go
Severity: Notice
Category: Best Practices
In Go, it is considered good practice to place the default case of a switch statement as the last case. The default case represents the code to be executed when none of the preceding cases match the switch expression. Here’s why it is recommended to put the default case last in a switch statement:
fallthrough
statements. Placing the default case last eliminates this ambiguity and helps prevent unintended behavior.Here’s an example illustrating the recommended order:
switch value {
case 1:
// Handle case 1
case 2:
// Handle case 2
default:
// Handle default case
}
In this way, the default case is positioned as the last option in the switch statement, clearly indicating it as the fallback when no other cases match.
By following the convention of placing the default case last in a switch statement, you enhance code readability, clarity, and maintainability. It ensures that the switch statement’s behavior is evident and reduces the likelihood of unintended fallthrough or confusion when modifying the code in the future.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
default:
// freebsd, openbsd,
// plan9 ...
fmt.Printf("%s.\n", os)
case "linux":
fmt.Println("Linux.")
case "windows":
fmt.Printf("Windows.")
}
}
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
}
}
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
}
}