On declaring variables

Go has several ways to declare a variable. Possibly there are more ways than are strictly required but with the Go 1 contract in effect it’s not going to change.

This short post gives examples of how I decide which variable declaration syntax to use. These are just suggestions, they make sense to me, but I’m sure others have equally strong justifications for alternative arrangements.

When declaring (but not initialising) a variable consider using this syntax

var num int

As Go does not permit uninitialised variables, num will be initialised to the zero value.

Some other examples of this form might be

var things []Thing // an empty slice of Things
for t := range ThingCreator() {
        things = append(things, t)

var thing Thing // empty Thing struct 
json.Unmarshall(reader, &thing)

The key is that var acts as a clue that the variable has been deliberately declared as the zero value of the indicated type.

When declaring and initialising, consider using the short declaration syntax. For example

num := rand.Int()

The lack of var is a signal that this variable has been initialised. I also find that by avoiding declaring the type of the variable and infering it from the right hand side of the assignment makes re-factoring easier in the future.

Of course, with any rule of thumb, there are exceptions.

min, max := 0, 1000

But maybe in this case min and max are really constants.

var length uint32 = 0x80

Here length may be being used with a library which requires a specific numeric type and this is probably more readable than

length := uint32(0x80)

2 thoughts on “On declaring variables

  1. JZA

    I am a bit confused with the use of := in what situations this is preferred and which others should I use var foo.

    Also could you give a quick definition of slice and structs (or link to it?), regards.

    1. Dave Cheney Post author

      I am a bit confused with the use of := in what situations this is preferred and which others should I use var foo.

      To summarise the post above, in a nutshell use var SOMEVARIABLE SOMETYPE when you want to declare SOMEVARIABLE as SOMETYPE for later us in your function. Conversely, use SOMEVARIABLE := SOME EXPRESSION to both declare and initialise SOMEVARIABLE to the result of SOME EXPRESSION.

Comments are closed.