草庐IT

go - 语法错误 : non-declaration statement outside function body at fmt. Println(words, length)

coder 2024-07-11 原文

我在 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: syntax error: non-declaration statement outside function body

我最近通过在任何函数之外使用 var 而不是 := 短语法来更正它,但错误与之前相同。

最佳答案

您的问题不在于变量声明,而在于 fmt.Println 行。您必须将其移动到函数内部:

func main() {
    fmt.Println(words, length)
}

在这里玩:
https://play.golang.org/p/JhUnNEIxIY

关于go - 语法错误 : non-declaration statement outside function body at fmt. Println(words, length),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633523/

有关go - 语法错误 : non-declaration statement outside function body at fmt. Println(words, length)的更多相关文章

随机推荐