doushi1473
2017-06-19 14:41
浏览 82
已采纳

语法错误:函数主体外的未声明语句位于fmt.Println(words,length)

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.

图片转代码服务由CSDN问答提供 功能建议

在旅途中的解释器中,我具有以下内容:

   package main 
 
import“ fmt” 
 
var someString =“一二三四” 
 
var单词= string.Fields(someString)
 
var长度= len(words)
 
fmt  .Println(单词,长度)
   
 
 

我得到

  tmp / sandbox216066597 / main.go:11: 语法错误:函数主体外的非声明语句
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanpu2272 2017-06-19 14:45
    最佳回答

    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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题