How to Use an if Statement with a Short Statement in Go
Go's if can run a short statement before its condition, separated by a semicolon: if n, err := strconv.Atoi(s); err == nil { ... }. The variables it declares exist only inside that if, which keeps them from leaking into the rest of the function.
Syntax
if <short statement>; <condition> {
// the variables from the short statement exist here
}
| Part | What it does |
|---|---|
<short statement> | Runs first, usually a := that calls a function. |
; | Separates it from the condition. |
<condition> | Tested next; it can use the variables just declared. |
| Scope | Those variables end with the if and its else branches. |
The Go specification: "The expression may be preceded by a simple statement, which executes before the expression is evaluated."
The Example
The example parses two pieces of text. The first parses, so the first if prints the number; the second doesn't, so the second if prints the error.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("Parsed:", n)
}
if _, err := strconv.Atoi("x"); err != nil {
fmt.Println("Failed:", err)
}
}
The second if keeps only the error, using _ for the number it doesn't need.
Step 2: Run It
go run main.go
Parsed: 42
Failed: strconv.Atoi: parsing "x": invalid syntax

Each if declared its own err, so the two never clashed. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using n after the if | undefined: n | Declare it before the if when you need it later |
| Putting a long computation in the short statement | The condition becomes hard to read | Keep it to one call |
| Forgetting the semicolon | syntax error: unexpected name err, expected { | Write statement; condition |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
undefined: <name> just after an if | The variable was declared in the if's short statement | Move the declaration above the if |
| A variable seems to lose its value | A short statement declared a new one with the same name | Use = instead of := for the outer variable |
FAQ
Do else branches see the variables too?
Yes. They're in scope in the if, every else if and the else.
Is this only for errors?
No, but checking an error right after a call is the most common use.
Conclusion
if v, err := f(); err != nil { ... } runs the call and tests its result in one line, and keeps v and err inside the if. Declare variables before the if when the code after it needs them.
Additional Resources
- If statements, in the Go specification.
- Effective Go: if.
