This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:go-best-practices/for-select-default-empty
Language: Go
Severity: Notice
Category: Best Practices
Description
In Go, the default case of a switch statement is executed when none of the preceding cases match the specified condition.
While it is technically allowed to have an empty default case, it is generally considered a bad practice because it can lead to confusion and make the code harder to read and maintain.
Here are a few reasons why the default case should not be empty in Go:
Clarity and readability: The primary goal of writing code is to make it understandable to other developers. Using an empty default case leaves the reader wondering why it is there and what its purpose might be. It is better to explicitly handle all possible cases, even if it means adding a placeholder or a comment.
Future-proofing: An empty default case can be a sign of incomplete or unfinished code. If new cases are added in the future and the default case remains empty, it may lead to unintended consequences or logic errors.
Linting and static analysis tools: Some linting tools and static analysis tools may flag empty default cases as potential mistakes or omissions. These tools can help identify and prevent potential bugs or issues in the code.
To address these concerns, it is recommended to either provide a meaningful action or simply include a comment in the default case explaining the reason for its presence. This helps improve code clarity, maintainability, and ensures proper handling of all possible cases in the switch statement.
Non-Compliant Code Examples
funcmain(){for{select{case<-myChannel:default:}}}
Compliant Code Examples
funcmain(){for{select{case<-myChannel:println("foo")default:println("bar")}}for{select{case<-myChannel2:println("foo")default:// println("bar")}}forsomething{select{case<-myChannel2:println("foo")default:}}select{case<-myChannel:default:}for{select{case<-myChannel:default:}println("foo")// another statement after for, no warning}}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- go-best-practices # Rules to enforce Go best practices.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다