var vs := in Go

Sudhir Jonathan picture Sudhir Jonathan · Feb 9, 2014 · Viewed 11.7k times · Source

In the Go web server example here: http://golang.org/doc/effective_go.html#web_server

The following line of code works

var addr = flag.String("addr", ":1718", "http service address")

but changing it to

addr := flag.String("addr", ":1718", "http service address")

is a compilation error. Why? Does it have anything to do with the face that the return type of the function is *string instead of string? What difference does that make?

UPDATE: Thanks for pointing out that := is not allowed at the top level. Any idea why this inconsistency is in the spec? I don't see any reason for the behaviour to be different inside a block.

Answer

publysher picture publysher · Feb 9, 2014

In Go, top-level variable assignments must be prefixed with the var keyword. Omitting the var keyword is only allowed within blocks.

package main

var toplevel = "Hello world"         // var keyword is required

func F() {
        withinBlock := "Hello world" // var keyword is not required
}