Skip to content
Latchkey

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.

go build
./config.go:6:1: syntax error: non-declaration statement outside function body

Common 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

  1. Find the statement the compiler flags.
  2. Wrap it in func init() or move it into the function it belongs to.
  3. For package-level initialization, use a var with an expression.
config.go
// 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 gofmt to expose brace imbalance.
  • Use init() for package setup that needs to run statements.
  • Build in CI so file-scope mistakes fail fast.

Frequently asked questions

What causes ""non-declaration statement outside function body""?
A statement like x = 1 or fmt.Println(...) was written outside a function, where only declarations are legal.
How do I fix "non-declaration statement outside function body"?
Move the statement into a function

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card