Variables
A free lesson from Swipe Coding · Go, level 2 · updated October 2026
By the Swipe team, founded by Colin · how we make lessons
The var keyword declares a variable with an explicit type: var name type = value. Once age is declared this way, it can only ever hold an int for the rest of its life — that's what being statically typed means in practice.
var age int = 25 fmt.Println(age)
If you give var an initial value, you can actually leave the type out entirely, and Go infers it from that value automatically — var name = "Maya" makes name a string without you writing string anywhere.
var name = "Maya" fmt.Println(name)
Inside a function, there's an even shorter way to declare a variable: the := short declaration operator. age := 25 declares age and infers its type in a single step — it's equivalent to var age = 25, just shorter to write, and it's the style most idiomatic Go code uses. The one catch is that := only works inside a function body, never at the package level.
age := 25 name := "Maya" fmt.Println(age, name)
Inside a function, the ____ operator declares a new variable and infers its type from the value on the right, all in one step.
Where can the := short variable declaration be used in Go?
One important gotcha: := always declares a brand-new variable, so using it a second time for the same name in the same scope is a compile error, since there's nothing new left to declare. To change an existing variable's value afterward, use the plain = operator instead, which reassigns without declaring anything.
age := 25 // age := 26 // compile error: no new variables on left side of := age = 26 // fine — reassigns the existing variable fmt.Println(age) // 26
Once a variable has been declared with :=, you can use := again on that same name to change its value later.
Keep your streak going in Swipe Coding
Swipe through every level of Go on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.
Get the Swipe apps →