Go "non-declaration statement outside function body" in CI
At file scope Go allows only declarations: package, import, const, var, type, and func. An assignment or call placed outside any function triggers this syntax error.
What this error means
Compilation fails with "syntax error: non-declaration statement outside function body", usually pointing at a line that should be inside a function.
./config.go:6:1: syntax error: non-declaration statement outside function bodyCommon causes
Executable code at package level
A statement like x = 1 or fmt.Println(...) was written outside a function, where only declarations are legal.
A misplaced brace dropped code out of its function
An early closing } ended the surrounding function, so the following statements landed at file scope.
How to fix it
Move the statement into a function
- Find the statement the compiler flags.
- Wrap it in
func init()or move it into the function it belongs to. - For package-level initialization, use a
varwith an expression.
// at file scope, use a declaration or init()
var defaultPort = 8080
func init() {
loadEnv()
}Fix a brace that closed a function early
Re-balance braces so the trailing statements stay inside their intended function.
How to prevent it
- Run
gofmtto expose brace imbalance. - Use
init()for package setup that needs to run statements. - Build in CI so file-scope mistakes fail fast.