语法错误:在 fmt.Println(words, length) 处,非声明语句在函数体外部。

huangapple go评论87阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年6月19日 22:41:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/44633523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定