dongqiao6730 2018-11-13 10:41
浏览 45
已采纳

声明后无法导入

I'm trying to import some modules after the declarations in Go.

For instance, I've tried importing the time time after declaring a variable but that doesn't work , can someone please tell me why that happens in Go?

This works:

package main

import (
       "fmt"
)
import "time";

var test = "testing"

func main() {
    currtime := time.Now()

    fmt.Println(test) 
    fmt.Println(currtime)//Output: 16:44:53

}

But thid doesn't:

package main

import (
       "fmt"
)

var test = "testing"
import "time"

func main() {
    currtime := time.Now()

    fmt.Println(test) 
    fmt.Println(currtime)//Output: 16:44:53

}

The error is "non-declaration statement outside function body". Why does that happen in Go?

  • 写回答

3条回答 默认 最新

  • douzhang1926 2018-11-13 11:20
    关注

    The error is "non-declaration statement outside function body". Why does that happen in Go?

    Because this is how Go is defined to work. From the spec:

    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.

    This means that the only valid place for import statements is between the package clause, and declarations of functions, types, variables, and constants.

    In your case, you have a variable declaration, so the Go compiler knows there will be no more import statements. Then it sees your erroneous import statement, sees that it is a non-declaration, and correctly generates the error you observe.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥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 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统