X := "somevalue" works in the main func, but not outside

Hi,

Occasional Go dabbler here so kindly pardon if this is obvious.

I am trying this with Go version 1.7.3 on Windows 7 (74 Bit):

package main

import "fmt"

x := "checkscope"

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

The editor shows this error ( i am using gvim 8 on Windows with the vim-go Plugin)
main.go|5 col 1| : expected declaration, found 'IDENT' x

And when I try to compile I get the following error:

C:\Users\ugrankar\src\golang-book\chapter3>go build main.go
# command-line-arguments
.\main.go:5: syntax error: non-declaration statement outside function body

I guess this means, the x:= “something” can be only used inside a function.

But then the following works without a problem:

package main

import "fmt"

var x string = "checkscope"

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

So is there something special about := that works only inside a function?

Regards,
pritesh

Yes. Short variable declarations may appear only inside functions.

What calmh said. This makes the parser simpler, you don’t need a symbol table if you require that each declaration at the top level being with one of the seven declaration keywords.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.