duanbo6482 2019-06-30 03:03
浏览 141
已采纳

语法错误:函数主体外的非声明语句,但所有内容都包含声明

This doesn't work:

package main

var formatter string = "fmt"

import (
    formatter
)

func main() {
    fmt.Println(formatter)
}

I got: syntax error: non-declaration statement outside function body

Even though everything there is declaration.

  • 写回答

1条回答 默认 最新

  • doutui2883 2019-06-30 03:16
    关注

    Per the Go specification:

    Each source file consists of a package clause defining the package to which it belongs, followed by a possibly empty set of import declarations that declare packages whose contents it wishes to use, followed by a possibly empty set of declarations of functions, types, variables, and constants.

    SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
    

    This means that top-level declarations such as var formatter string = "fmt" must come after any import declarations, if any import declarations are present. Technically, you're getting this error because the definition of declaration does not include import declarations (despite the name), and your source code has an import declaration after a top-level declaration, where an import declaration is not allowed to be.

    Furthermore, the Import declarations section shows that import paths must be string literals, so even if it weren't for the ordering issue, you still wouldn't be able to do what you're attempting.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?