Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Variables & Basic Types · Lesson 7 of 9

Variables

A free lesson from Swipe Coding · Go, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
Go gives you two ways to create a variable — you'll use both, in different places. 🐹

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)
var age int = 25 declares a variable named age, fixes its type as int, and gives it an initial value of 25.

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)
Go infers that name is a string purely from the value "Maya", without an explicit type annotation.
🤖
This is the shortcut you'll actually reach for most of the time. ⚡

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)
:= declares both variables and infers their types in one step, entirely inside main() or another function.
Fill in the blank

Inside a function, the ____ operator declares a new variable and infers its type from the value on the right, all in one step.

Quick check

Where can the := short variable declaration be used in Go?

🤖
Mix this one up and the compiler will stop you cold — that's actually a good thing. 🛑

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
The second := fails because age already exists. Plain = is the correct way to update it afterward.
True or false

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 →