LESSON · 1 OF 23

The var declaration

The var declaration

Go is statically typed - every variable has a type, fixed when you declare it. The explicit way to declare one uses the var keyword, a name, and a type:

go
var name string = "web-01"
var count int = 3

Go can usually work out the type from the value on the right, so you can drop the type and let it be inferred:

go
var name = "web-01"   // type inferred as string
var count = 3         // inferred as int

You can also declare a variable with no value at all. It is not left undefined - it gets the type's zero value instead (a later node covers what those are):

go
var count int         // count is 0

So var has three shapes: with a type and value, with just a value and an inferred type, or with just a type and no value.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute