The var Statement

How to declare variables in Go using the var statement - explicit types, inferred types, zero values, factored blocks, and package-level variables

The var keyword is Go's explicit way to bring a variable into existence. You write var, then the name, then optionally a type and a starting value. It is the only declaration form that works everywhere: at package level and inside functions. When you see var in Go code, read it as a deliberate statement that a variable exists now, with a known type and a known starting value.

The Smallest Working Version

Here is a complete program that uses the three basic var forms:

package main

import "fmt"

func main() {
	var temperature float64 = 23.5
	var city = "Lisbon"
	var isReady bool
	fmt.Println(temperature, city, isReady)
}

Run it with go run . and you see:

23.5 Lisbon false

The first line gives the type and the value. The second line gives only a value, so the compiler infers the type string from "Lisbon". The third line gives only a type, so isReady starts at the zero value for bool, which is false. All three variables are fully declared and safe to read from the moment the lines run.

The Four Forms of var

Every var declaration is one of four shapes. The shape you pick says something about what you know at the point of declaration.

var count int = 10       // type and value
var name = "Faro"        // value only, type inferred as string
var total int            // type only, starts at the zero value 0
var a, b int = 1, 2      // two variables at once, same type

A var with a type and a value is the most explicit form. Use it when the type matters for reading the code, for example when the value alone does not make the type obvious. A var with a value but no type lets the compiler infer the type. That is the same inference the short declaration operator uses, but written out in full.

A var with a type but no value declares the variable and gives it the zero value of that type. This is the form you reach for when you need the variable to exist before you know its value, for example a counter you will fill inside a loop or a result you will assign after a check. There is no way to write this shape without var: the short declaration operator always needs a value.

You can also declare several variables on one line when they share a type. The number of values must match the number of names.

var works everywhere:

Unlike the short := declaration, var is legal at package level. When you need a variable that lasts the entire program and is not tied to one function, var is your only option.

Grouping Declarations in a Factored Block

When several variables belong together, you can group them in one var block with parentheses. This is common at package level for configuration values:

package main

import (
	"fmt"
	"time"
)

var (
	maxWorkers   int           = 10
	defaultName  string        = "guest"
	retryTimeout time.Duration = 2 * time.Second
)

func main() {
	fmt.Println(maxWorkers, defaultName, retryTimeout)
}

Running this prints:

10 guest 2s

The block groups related configuration and signals that these variables belong together. Inside a block you can mix explicit and inferred types freely, and each line follows the same rules as a standalone var. Note that the block needs the time import because retryTimeout uses time.Second. A var block is purely organizational: it does not change what the variables mean or how long they live.

Grouping signals intent:

When a reader sees a factored var block, they understand at a glance that the values form one configuration set. Prefer a block over scattered package-level declarations when the variables are changed together.

var at Package Level and Inside Functions

A var at package level, written outside any function, is visible to every file in the same package. It lives for the whole run of the program. A var inside a function is visible only from its declaration to the end of the enclosing braces, and a fresh copy is created each time the function runs.

package main

import "fmt"

var greeting = "hello from the package"

func main() {
	var local = "hello from main"
	fmt.Println(greeting)
	fmt.Println(local)
}

This prints both lines. The package-level greeting could also be read from any other function in the same package, while local exists only inside main. Package-level variables are shared mutable state, so keep them few and give them clear names. Most variables in a Go program are local.

var and the Short Declaration

Go has a second declaration form, the short declaration operator :=, which declares and initializes a variable in one compact step inside a function. The two forms overlap but are not interchangeable. Use := when you are inside a function and you have the value right now. Use var when you are at package level, when you need the zero value first and will assign later, or when writing the type out makes the code clearer. A typical function mixes both: var for a variable that accumulates results across a loop, := for intermediate values.

Common Mistakes

Using := at package level. The short declaration only works inside functions. At package level, every statement must start with a keyword such as var, func, const, or import. This code does not compile:

package main

count := 10 // compile error: non-declaration statement outside function body

The fix is to write var count = 10.

Declaring the same name twice in one block. A var declaration always creates a new variable, so repeating a name in the same block is an error:

var x = 1
var x = 2 // compile error: x redeclared in this block

To change the value, assign with = instead: x = 2.

Leaving out the type when there is no value. A var with no initial value must carry a type, because the compiler has nothing to infer from:

var count // compile error: syntax error: unexpected newline, expected type

Write var count int instead, and count starts at 0.

Package-level := is illegal:

Using := outside a function body produces a syntax error. If you need a package-level variable, use var. This is one of the most common surprises for newcomers.

A Complete Example

Here is everything on this page in one program: package-level configuration in a factored block, local variables in all four var forms, and a zero value that gets filled in later.

package main

import (
	"fmt"
	"time"
)

var (
	appName      = "greeter"
	defaultTries = 3
	timeout      = 2 * time.Second
)

func main() {
	var greeting string = "Hello"
	var name = "Gopher"
	var tries int
	var a, b int = 1, 2
	for tries < defaultTries {
		tries++
	}
	fmt.Println(greeting, name, tries, a+b, timeout)
}

Running it prints:

Hello Gopher 3 3 2s

The package-level block holds settings the whole program shares. Inside main, greeting states its type, name lets the compiler infer string, tries starts at 0 and is filled by the loop, and a, b are declared together. Each form earns its place by saying something the others do not.

Summary

The var statement is Go's explicit declaration: a name, an optional type, and an optional starting value, usable at package level and inside functions. Its four forms cover every situation where you know the type, know the value, know only one of them, or want several variables at once. Factored blocks group related declarations, package-level var creates program-wide state, and a var with no value gives you the zero value to fill in later. The habit to build is choosing the form that says the most with the least noise: var when the type or the zero value is the point, and the short declaration when the value is already in your hand.