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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号