go-control-flowlisted
Install: claude install-skill dwana1/golang-skills
# Go Control Flow
> **Source**: Effective Go. Go's control structures are related to C but differ
> in important ways. Understanding these differences is essential for writing
> idiomatic Go code.
Go has no `do` or `while` loop—only a generalized `for`. There are no
parentheses around conditions, and bodies must always be brace-delimited.
---
## If Statements
### Basic Form
Go's `if` requires braces and has no parentheses around the condition:
```go
if x > 0 {
return y
}
```
### If with Initialization
`if` and `switch` accept an optional initialization statement. This is common
for scoping variables to the conditional block:
```go
// Good: err scoped to if block
if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
```
### Omit Else for Early Returns
When an `if` body ends with `break`, `continue`, `goto`, or `return`, omit the
unnecessary `else`. This keeps the success path unindented:
```go
// Good: no else, success path at left margin
f, err := os.Open(name)
if err != nil {
return err
}
codeUsing(f)
```
```go
// Bad: else clause buries normal flow
f, err := os.Open(name)
if err != nil {
return err
} else {
codeUsing(f) // unnecessarily indented
}
```
### Guard Clauses for Error Handling
Code reads well when the success path flows down the page, eliminating errors as
they arise:
```go
// Good: guard clauses eliminate errors early
f, err := os.Open(name)
if err != nil {
return err
}
d, err := f.Stat()
if err != nil