2017-06-19 85 views
-4

我在解釋中去的遊覽以下幾點:語法錯誤:非聲明語句外部函數體在fmt.Println(即長度)

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而不是:=在任何函數之外的簡短語法來更正它,但錯誤與以前相同。

+2

您必須添加一個'主()'函數,那是你的程序的入口點。您必須將'fmt.Println()'移動到這個'main()'函數中。閱讀[規範:程序執行](https://golang.org/ref/spec#Program_execution)。如果您是Go的新手,請先參加[Go Tour](https://tour.golang.org/welcome/1)。你不會奇蹟般地猜測Go語法。 – icza

+0

正如問題中所述,我正在去旅行。這很有效,如果你想要,我會接受 – codyc4321

+0

你說得對,我錯過了你的問題的一部分。 – icza

回答

2

你的問題不是與變量聲明,它是與fmt.Println行。你必須移動功能的這裏面:

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

GoPlay這裏:
https://play.golang.org/p/JhUnNEIxIY

+0

謝謝你的禮貌。我會接受,當它讓我 – codyc4321