Lesson 3 of 20 · Part 1: Getting started
Variables and constants
Learn Go variables and constants for beginners. Use var, the := short declaration, zero values, scope, const and iota, with runnable examples.
6 min read · Updated · Beginner friendly
What you'll learn
- Declare variables with var and :=
- Know the zero value of each basic type
- Understand scope and avoid accidental shadowing
- Use constants and iota for fixed values
Programs work with data: a user’s name, a price, a score. A variable is a named box that holds a value. You can read the value and replace it as the program runs. A constant is a box whose value can never change.
Declaring a variable with var
The full way to declare a variable uses the var keyword, a name and a type:
package main
import "fmt"
func main() {
var name string = "Gopher"
var age int = 14
fmt.Println(name, "is", age, "years old")
age = 15 // assign a new value with =
fmt.Println(name, "is now", age)
}Gopher is 14 years old
Gopher is now 15Read var age int = 14 as “declare a variable called age, of type int, with the value 14.” Notice that in Go the type comes after the name.
Once a variable has a type, it keeps it. You can store another int in age, but not a string:
package main
func main() {
var age int = 14
age = "fifteen"
_ = age
}cannot use "fifteen" (untyped string constant) as int value in assignmentThis is what statically typed means: the compiler checks types before your program runs, so whole groups of bugs never reach your users.
Letting Go infer the type
If you give a starting value, you can leave out the type. Go works it out from the value:
var city = "Chennai" // string
var year = 2026 // int
var price = 9.99 // float64The short declaration :=
Inside a function, there is an even shorter form that you will use most of the time:
package main
import "fmt"
func main() {
language := "Go"
version := 1.27
stable := true
fmt.Println(language, version, stable)
}Go 1.27 true:= means “declare and assign”. It creates a new variable and infers its type from the value.
| Form | Where it can be used | Typical use |
|---|---|---|
var x int = 5 |
Anywhere | When you want to state the type clearly |
var x = 5 |
Anywhere | Package-level variables |
var x int |
Anywhere | When the starting value should be the zero value |
x := 5 |
Inside functions only | Most local variables |
= versus :=
:= creates a new variable. = changes an existing one. Using := twice for the same name in the same block is an error (no new variables on left side of :=), and using = on a name that doesn’t exist yet is also an error (undefined: x).
Zero values
What happens if you declare a variable without a value? In some languages it contains random garbage or undefined. In Go, every variable starts with a well-defined zero value:
package main
import "fmt"
func main() {
var count int
var price float64
var name string
var ready bool
fmt.Println(count, price, ready)
fmt.Printf("name is %q\n", name) // %q shows the quotes, so we can see it's empty
}0 0 false
name is ""| Type | Zero value |
|---|---|
Numbers (int, float64, …) |
0 |
string |
"" (empty string) |
bool |
false |
| Pointers, slices, maps, channels, functions, interfaces | nil |
Zero values are useful: a counter that starts at 0 or a flag that starts as false needs no extra code.
Declaring several variables at once
You can declare several variables on one line, or group them in a block:
package main
import "fmt"
func main() {
var width, height = 1920, 1080
first, last := "Ada", "Lovelace"
var (
host = "localhost"
port = 8080
verbose = false
)
fmt.Println(width, height)
fmt.Println(first, last)
fmt.Println(host, port, verbose)
}1920 1080
Ada Lovelace
localhost 8080 falseAssigning several values at once makes it easy to swap two variables, with no temporary variable needed:
package main
import "fmt"
func main() {
a, b := "left", "right"
a, b = b, a
fmt.Println(a, b)
}right leftNaming variables
- A name starts with a letter or
_, followed by letters, digits or_:total,user2,max_size. - Names are case sensitive:
countandCountare different variables. - Go style uses camelCase:
userName, notuser_name. - Short names are fine for short-lived variables (
i,n,err); use descriptive names for things that live longer (retryCount,customerEmail). - A name starting with a capital letter is exported: visible to other packages. You will use this in lesson 15.
Unused variables are an error
Go refuses to compile a program with a local variable that is declared but never used:
package main
import "fmt"
func main() {
total := 10
discount := 2
fmt.Println(total)
}declared and not used: discountThis catches typos and leftover code early. If you really need to ignore a value, assign it to the blank identifier _, which throws it away.
Scope: where a variable can be seen
A variable is only visible inside the block ({ ... }) where it is declared, and in blocks nested inside it. This region is called its scope.
package main
import "fmt"
var appName = "t2run" // package level: visible in every function of this package
func main() {
message := "hello" // visible anywhere inside main
if true {
inner := "only inside this if block"
fmt.Println(appName, message, inner)
}
// fmt.Println(inner) would not compile: inner is out of scope here
fmt.Println(appName, message)
}t2run hello only inside this if block
t2run helloWatch out for shadowing
If you use := inside an inner block with a name that already exists outside, you create a new variable that hides (shadows) the outer one. This is a classic beginner bug:
package main
import "fmt"
func main() {
score := 10
if score > 5 {
score := 100 // oops: a NEW variable, only inside this block
fmt.Println("inside:", score)
}
fmt.Println("outside:", score) // still 10!
}inside: 100
outside: 10To change the outer variable, use = instead: score = 100.
Constants
Use const for values that should never change, such as configuration or mathematical values:
package main
import "fmt"
const Pi = 3.14159
const appVersion = "2.1.0"
func main() {
const radius = 2.0
area := Pi * radius * radius
fmt.Println("version", appVersion)
fmt.Println("area:", area)
}version 2.1.0
area: 12.56636Trying to change a constant is a compile error (cannot assign to Pi). Constants must be known when the program is compiled, so you can’t set one from user input or a function call that runs while the program is running.
Untyped constants
A constant such as const Pi = 3.14159 has no fixed type until you use it. It adapts to the expression it appears in, which is why Pi * radius works without any conversion. This makes constants very convenient for numbers.
iota: numbering constants automatically
When you need a set of related constants with increasing values, such as days of the week or log levels, use iota in a const block. It starts at 0 and goes up by one on each line:
package main
import "fmt"
const (
Low = iota // 0
Medium // 1
High // 2
Critical // 3
)
func main() {
fmt.Println(Low, Medium, High, Critical)
}0 1 2 3Lines after the first repeat the same expression automatically, so iota can also be used in calculations. Here each size is 1024 times bigger than the one before:
package main
import "fmt"
const (
_ = iota // skip 0 with the blank identifier
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)
func main() {
fmt.Println("KB:", KB)
fmt.Println("MB:", MB)
fmt.Println("GB:", GB)
}KB: 1024
MB: 1048576
GB: 1073741824<< shifts bits to the left; 1 << 10 is 2¹⁰ = 1024. You don’t need to master bit shifting now. Just remember that iota saves you from numbering constants by hand.
Putting it together
A small program that works out a shopping bill:
package main
import "fmt"
const taxRate = 0.18 // 18% tax
func main() {
item := "Running shoes"
price := 2499.0
quantity := 2
subtotal := price * float64(quantity)
tax := subtotal * taxRate
total := subtotal + tax
fmt.Println("Item: ", item)
fmt.Println("Subtotal:", subtotal)
fmt.Println("Tax: ", tax)
fmt.Println("Total: ", total)
}Item: Running shoes
Subtotal: 4998
Tax: 899.64
Total: 5897.64float64(quantity) converts the whole number quantity into a decimal number so it can be multiplied by price. Go never mixes types silently; you will learn more about conversions in the next lesson.
Exercises
1. Swap without a temporary variable. Declare x := 3 and y := 7, swap their values in one line, and print them.
Show solution
package main
import "fmt"
func main() {
x, y := 3, 7
x, y = y, x
fmt.Println("x =", x, "y =", y)
}x = 7 y = 32. Circle calculator. Using a constant for π (3.14159) and a variable radius := 5.0, print the circle’s circumference (2πr) and area (πr²).
Show solution
package main
import "fmt"
const Pi = 3.14159
func main() {
radius := 5.0
circumference := 2 * Pi * radius
area := Pi * radius * radius
fmt.Println("circumference:", circumference)
fmt.Println("area:", area)
}circumference: 31.4159
area: 78.53975The standard library also has a precise value in math.Pi; you will meet the math package in the next lesson.
3. Days of the week. Use iota to create constants Sunday to Saturday and print Wednesday. What number does it print, and why?
Show solution
package main
import "fmt"
const (
Sunday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func main() {
fmt.Println("Wednesday =", Wednesday)
}Wednesday = 3It prints 3 because iota starts at 0 for Sunday and increases by one on each line.
4. Find the bug. This program should print total: 30, but it prints total: 0. Why?
package main
import "fmt"
func main() {
total := 0
if true {
total := 10 + 20
_ = total
}
fmt.Println("total:", total)
}Show solution
The := inside the if block creates a new total that shadows the outer one. The outer total is never changed. Use = instead: total = 10 + 20 (and remove the _ = total line).
Recap
var name type = valueis the full form;name := valueis the short form inside functions.- Every variable has a zero value:
0,"",falseornil. - Unused local variables are a compile error;
_discards a value. - A variable is visible only in its block. Beware of
:=shadowing an outer variable. constdeclares values that never change, andiotanumbers them for you.
Next, you will look more closely at Go’s basic types: numbers, strings and booleans.
Finished this lesson?
Your progress is saved in this browser only.