语法错误:函数主体外的非声明语句,但所有内容都包含声明

This doesn't work:

package main

var formatter string = "fmt"

import (
    formatter
)

func main() {
    fmt.Println(formatter)
}

I got: syntax error: non-declaration statement outside function body

Even though everything there is declaration.

Per the Go specification:

Each source file consists of a package clause defining the package to which it belongs, followed by a possibly empty set of import declarations that declare packages whose contents it wishes to use, followed by a possibly empty set of declarations of functions, types, variables, and constants.

SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .

This means that top-level declarations such as var formatter string = "fmt" must come after any import declarations, if any import declarations are present. Technically, you're getting this error because the definition of declaration does not include import declarations (despite the name), and your source code has an import declaration after a top-level declaration, where an import declaration is not allowed to be.

Furthermore, the Import declarations section shows that import paths must be string literals, so even if it weren't for the ordering issue, you still wouldn't be able to do what you're attempting.