fmt.Println 必须在 Go 的函数内吗?

Does fmt.Println have to be inside a function in Go?

fmt.Println 是否需要始终属于一个函数?

之前使用过 Python 并且它允许,但在研究中,似乎 Java 没有

fmt.Println("can I do it?")

Returns:

syntax error: non-declaration statement outside function body

它可能在一个函数之外,看这个例子:

var n, err = fmt.Println("I can do it")

func main() {
    fmt.Println("In main(),", n, err)
}

它输出(在 Go Playground 上尝试):

I can do it
In main(), 12 <nil>

(输出值 12 <nil> 是第一个 fmt.Println() 调用的值 return,它写入的字节数和它 return 的错误这是 nil 表示没有错误。)

另请注意,您甚至不必存储 fmt.Prinln() 的 return 值,您可以像这样使用 blank identifier

var _, _ = fmt.Println("I can do it")

它不能在顶层“介于”top-level 声明之间独立存在,但上面的变量声明(带有空白标识符)几乎可以实现相同的效果。

Spec: Source file organization:

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 ";" } .

显然是 package clause or import declaration can't contain an fmt.Println() call, and the top level declarations:

Declaration   = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl  = Declaration | FunctionDecl | MethodDecl .

A constant declaration cannot contain an fmt.Println() call, that's not a constant expression. A type declaration 也不能包含函数调用。

变量声明可以,如答案顶部的示例所示。

Function and method declarations 也可以调用 fmt.Println(),但您具体询问是否可以在它们之外调用 fmt.Println()

因此,在顶层允许的函数之外唯一允许的地方是在变量声明中。

go总是在main函数中开始执行,所以fmt.Println()需要在main函数中或者在main函数中调用。