SKY-G203 · Go-specific rules
Go defer inside a loop
In Go, defer runs a call when the surrounding function returns, not when the current loop iteration ends. A defer f.Close() inside a loop keeps every file open until the whole function finishes. SKY-G203 reports a defer inside a for or range loop unless a return follows it in the same loop body.
- Languages
- Go
- Quality gate
- counted toward the gate limits (full and diff scans)
- Finding type
- review
- Catalog name
- Go defer in loop
Why it matters
A loop over thousands of files can fail with "too many open files". With mu.Lock(); defer mu.Unlock() in a loop, the second iteration waits for a lock that is only released when the function returns, so it deadlocks.
What Skylos flags
package handlers import ( "archive/zip" "io" "os") func ExportReports(zw *zip.Writer, paths []string) error { for _, p := range paths { f, err := os.Open(p) if err != nil { return err } defer f.Close() w, err := zw.Create(p) if err != nil { return err } if _, err := io.Copy(w, f); err != nil { return err } } return nil}What Skylos leaves alone
package handlers import ( "encoding/json" "os") type ExportConfig struct { Format string `json:"format"`} // LoadExportConfig reads the first config file that exists.func LoadExportConfig(candidates []string) (*ExportConfig, error) { for _, path := range candidates { f, err := os.Open(path) if err != nil { continue } defer f.Close() var cfg ExportConfig err = json.NewDecoder(f).Decode(&cfg) return &cfg, err } return nil, os.ErrNotExist}Why Skylos leaves it alone
The defer is followed by a return in the same loop body, so it can run at most once: the function ends in the same iteration that opened the file.
How Skylos decides
- Runs with
--danger. The bundled Go engine,skylos-go, parses each.gofile with Go's own parser._test.gofiles, symbolic links and files undervendor,testdata,node_modulesand hidden folders are skipped; generated files are checked. Ago.modis not required. - Walks each function body, and separately each function literal, keeping track of the
forandrangeloops around every statement (three-clause loops andfor {}count too). - Stops at a function literal inside the loop:
go func() { defer wg.Done() }()and per-iteration closures have their own defers and are not reported. - Reports a
deferwith a loop around it unless it is a direct statement of the innermost loop body and is followed, later in that same body, by areturn, or by a plainbreakwhen only one loop encloses it. It does not check whether acontinuein between can skip that exit. - Reports MEDIUM. The ID stays SKY-G203 in the output: Go findings that have a cross-language rule are renamed (Go SQL injection SKY-G211 is reported as SKY-D211), but defer-in-loop has none.
How to fix it
Move the loop body into its own function, so each defer runs when that call returns, once per iteration. Closing the file explicitly before the next iteration also works.
package handlers import ( "archive/zip" "io" "os") func ExportReports(zw *zip.Writer, paths []string) error { for _, p := range paths {Removed: f, err := os.Open(p)Removed: if err != nil {Removed: return errRemoved: }Removed: defer f.Close()Removed: w, err := zw.Create(p)Removed: if err != nil {Removed: return errRemoved: }Removed: if _, err := io.Copy(w, f); err != nil {Added: if err := addReport(zw, p); err != nil { return err } } return nil}Added: Added: func addReport(zw *zip.Writer, p string) error {Added: f, err := os.Open(p)Added: if err != nil {Added: return errAdded: }Added: defer f.Close()Added: w, err := zw.Create(p)Added: if err != nil {Added: return errAdded: }Added: _, err = io.Copy(w, f)Added: return errAdded: }When it can be wrong
- A
deferinside anifblock in the loop, followed by areturnin that block, is reported even though it runs once: Skylos only looks at direct statements of the loop body. - A labelled
break outeris reported even when it leaves the only loop. - It misses a
deferfollowed by anif … { continue }and then areturn: thecontinuelets thedeferrun again, but the laterreturncounts as the exit.
Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.
How to silence it
On the
deferline; a comment on the line above is not read:Go defer f.Close() // skylos: ignore[SKY-G203] the loop returns after the first match[tool.skylos] ignore = ["SKY-G203"](the ID in upper case) turns the rule off. A baseline accepts existing findings, but it records the absolute file path and the line, so an entry stops matching when the checkout moves or the line shifts.