英文:
Syntax error: non-declaration statement outside function body at fmt.Println(words, length)
问题
我在Go语言的解释器中有以下内容:
package main
import "fmt"
var someString = "one two three four "
var words = strings.Fields(someString)
var length = len(words)
fmt.Println(words, length)
我得到了以下错误信息:
tmp/sandbox216066597/main.go:11: 语法错误:非声明语句在函数体外部
最近我通过在任何函数外部使用var
而不是:=
的简短语法来进行了更正,但错误与之前相同。
英文:
I have the following in the interpreter in the tour of go:
package main
import "fmt"
var someString = "one two three four "
var words = strings.Fields(someString)
var length = len(words)
fmt.Println(words, length)
I get
tmp/sandbox216066597/main.go:11: syntax error: non-declaration statement outside function body
I recently corrected it by using var
instead of :=
short syntax outside of any functions, but the error is the same as before.
答案1
得分: 4
你的问题不在于变量声明,而是在于 fmt.Println 这一行。你必须将其放在一个函数内部:
func main() {
fmt.Println(words, length)
}
在 GoPlay 上测试代码:
https://play.golang.org/p/JhUnNEIxIY
英文:
Your issue isn't with the variable declarations, it's with the fmt.Println line. You must move this inside of a function:
func main() {
fmt.Println(words, length)
}
GoPlay here:
https://play.golang.org/p/JhUnNEIxIY
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论