声明后无法导入

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?

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.

You usually have two ways to import packages in Go:

import "fmt"
import "time" 

Or

import (
    "fmt"
    "time"
)

The trick is that you cannot have a mix of import and something else like in your second example.

package main

import (
       "fmt"
)

var test = "testing" //<-- This does not comply with the definition of a Go file
import "time"

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

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

}

Here you can find a well done documentation of the Anatomy of .go file.

Structure of every .go file is the same.

  • First is package clause optionally preceded with comments usually describing the purpose of the package.

  • Then zero or more import declarations.

  • 3rd section contains zero or more top-level declarations

why does that happen in go lang ?

Because it is disallowed by the language spec. Pretty simple, or?