这行不通:
package main
var formatter string = "fmt"
import (
formatter
)
func main() {
fmt.Println(formatter)
}
我得到:语法错误:函数体之外的非声明语句
即使一切都有声明。
最佳答案
根据 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 ";" } .
这意味着如果存在任何导入声明,则顶级声明(例如 var formatter string = "fmt")必须在任何导入声明之后。从技术上讲,您收到此错误是因为 declaration 的定义不包括导入声明(尽管名称),并且您的源代码在顶级声明之后有一个导入声明,其中不允许有导入声明。
此外,Import declarations section显示导入路径必须是字符串文字,因此即使不是顺序问题,您仍然无法执行您正在尝试的操作。
关于go - 语法错误 : Non-declaration statement outside function body, 但所有内容都有声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822134/