Non-declaration statement outside function body

yourbasic.org/golang

As you may have noticed, a program with short variable declarations outside a function doesn’t compile.

package main

n := 1 // illegal

func main() {}
../main.go:3:1: syntax error: non-declaration statement outside function body

Short variable declarations can only be used inside functions. You have to write

package main

var n = 1

func main() {}

This is a trade-off in the design of the Go language.

At the top level, every declaration begins with a keyword. This simplifies parsing. golang-nuts forum: Ian Lance Taylor

Further reading

Learn to love your compiler is a list of common Go compiler error messages: what they mean and how to fix the problem.

Share this page: