";let n=document.getElementById("TableOfContents");n&&(n.innerHTML=e)}rerender(){this.renderFilterMenu(),this.renderPageContent(),this.populateRightNav(),this.runHooks("afterRerender")}renderPageContent(){let e={};Object.keys(this.ifFunctionsByRef).forEach(t=>{let s=this.ifFunctionsByRef[t],o=s.value,n=(0,h.reresolveFunctionNode)(s,{variables:this.selectedValsByTraitId});this.ifFunctionsByRef[t]=n,o!==n.value&&(e[t]=n.value)});let t=document.getElementsByClassName("cdoc__toggleable");for(let n=0;n{this.fitCustomizationMenuToScreen()})}addDropdownEventListeners(){let e=document.getElementsByClassName("cdoc-dropdown");for(let t=0;t{let t=e.target;for(;!t.classList.contains("cdoc-dropdown")&&t.parentElement;)t=t.parentElement;let n=t.classList.toggle("cdoc-dropdown__expanded");t.setAttribute("aria-expanded",n.toString())});document.addEventListener("keydown",e=>{if(e.key==="Enter"){let t=e.target;t.classList.contains("cdoc-filter__option")&&t.click()}}),document.addEventListener("click",t=>{for(let n=0;nthis.handleFilterSelectionChange(e));this.addDropdownEventListeners()}locateFilterSelectorEl(){let e=document.getElementById("cdoc-selector");return!!e&&(this.filterSelectorEl=e,!0)}applyFilterSelectionOverrides(){let s=Object.keys(this.selectedValsByTraitId),e=!1,t=this.browserStorage.getTraitVals();Object.keys(t).forEach(n=>{s.includes(n)&&this.selectedValsByTraitId[n]!==t[n]&&(this.selectedValsByTraitId[n]=t[n],e=!0)});let n=(0,j.getTraitValsFromUrl)({url:new URL(window.location.href),traitIds:s});return Object.keys(n).forEach(t=>{this.selectedValsByTraitId[t]!==n[t]&&(this.selectedValsByTraitId[t]=n[t],e=!0)}),e}updateEditButton(){let t=document.getElementsByClassName("toc-edit-btn")[0];if(!t)return;let e=t.getElementsByTagName("a")[0];e&&(e.href=e.href.replace(/\.md\/$/,".mdoc.md/"))}revealPage(){this.runHooks("beforeReveal"),this.filterSelectorEl&&(this.filterSelectorEl.style.position="sticky",this.filterSelectorEl.style.backgroundColor="white",this.filterSelectorEl.style.paddingTop="10px",this.filterSelectorEl.style.visibility="visible",this.filterSelectorEl.style.zIndex="1000");let e=document.getElementById("cdoc-content");e&&(e.style.visibility="visible"),this.runHooks("afterReveal")}renderFilterMenu(){if(!this.filterSelectorEl||!this.filtersManifest)throw new Error("Cannot render filter selector without filtersManifest and filterSelectorEl");let e=(0,l.resolveFilters)({filtersManifest:this.filtersManifest,valsByTraitId:this.selectedValsByTraitId});Object.keys(e).forEach(t=>{let n=e[t];this.selectedValsByTraitId[t]=n.currentValue});let t=(0,y.buildCustomizationMenuUi)(e);this.filterSelectorEl.innerHTML=t,this.fitCustomizationMenuToScreen(),this.addFilterSelectorEventListeners()}fitCustomizationMenuToScreen(){let e=document.getElementById(g);if(!e)return;let s=e.classList.contains(n),t=document.getElementById(v);if(!t)throw new Error("Dropdown menu not found");let o=document.getElementById(b);if(!o)throw new Error("Menu wrapper not found");let i=e.scrollWidth>o.clientWidth;!s&&i?(e.classList.add(n),t.classList.remove(n)):s&&!i&&(e.classList.remove(n),t.classList.add(n))}get cdocsState(){return{selectedValsByTraitId:this.selectedValsByTraitId,ifFunctionsByRef:this.ifFunctionsByRef,filtersManifest:this.filtersManifest,browserStorage:this.browserStorage,filterSelectorEl:this.filterSelectorEl}}};e.ClientFiltersManager=r,t=r,s={value:void 0}}),y=e(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=j();window.clientFiltersManager=t.ClientFiltersManager.instance}),y()})()The default case of a switch should be first or last
This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:go-best-practices/switch-default-first-or-last
Language: Go
Severity: Notice
Category: Best Practices
Description
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:
Readability: Placing the default case last improves code readability by following a logical flow. When reviewing the code, developers expect to see any explicit cases before the default case. It makes the switch statement easier to understand and follow the intended logic.
Clarity of intention: By positioning the default case at the end, it clearly communicates to other developers that it is the fallback option when none of the specific cases match. It prevents confusion and ensures that developers understand how the switch statement behaves.
Avoiding unintended fallthrough: In Go, switch statements do not fall through to the next case by default. When the default case is placed before other cases, there is a risk of unintentionally executing the default case when a match occurs earlier due to omitted or misplaced fallthrough statements. Placing the default case last eliminates this ambiguity and helps prevent unintended behavior.
Refactoring and maintenance: Placing the default case at the end simplifies future code changes and refactoring. When inserting or rearranging cases, it is easier to maintain the intended logic and ensure that specific cases take precedence over the default case.
Here’s an example illustrating the recommended order:
switchvalue{case1:// Handle case 1case2:// Handle case 2default:// 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.
Non-Compliant Code Examples
packagemainimport("fmt""runtime")funcmain(){fmt.Print("Go runs on ")switchos:=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.")}}
Compliant Code Examples
packagemainimport("fmt""runtime")funcmain(){fmt.Print("Go runs on ")switchos:=runtime.GOOS;os{case"darwin":fmt.Println("OS X.")case"linux":fmt.Println("Linux.")default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.\n",os)}}
packagemainimport("fmt""runtime")funcmain(){fmt.Print("Go runs on ")switchos:=runtime.GOOS;os{default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.\n",os)case"darwin":fmt.Println("OS X.")case"linux":fmt.Println("Linux.")}}
원활한 통합. 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 검사를 추가합니다