Explain it simply
Variables, simply
Think of a variable as a labeled box that holds one piece of data. In Go every box has a shape called its type: a box for integers cannot hold text.
There are two ways to make a new box. `var` works anywhere, with or without a written type. `:=` is a shortcut that only works inside functions. And Go has no empty boxes: even before you store anything, a variable holds its type's zero value, such as 0 for numbers and "" for text.
Problem → Why → Solution
The problem: := outside a function will not compile
You need a counter the whole program can use, so you write `count := 0` above `main`. It is the same syntax that always works inside functions, so you expect it to work here too. Instead the compiler rejects it with 'non-declaration statement outside function body'.
package main
import "fmt"
count := 0 // package level
func main() {
fmt.Println(count)
}
// ./main.go:5:1: syntax error: non-declaration statement outside function bodyWhy this happens
Outside functions, at package level, only declarations that start with a keyword are allowed: `var`, `const`, `func`, `type` and `import`. `:=` is a statement called a short variable declaration, and statements may only appear inside a function body. Write `var count = 0` at package level instead.
Core concept: declaration, zero values and assignment
Go has four ways to declare a variable, and each one has a place where it fits best.
| Form | When to use it |
|---|---|
| var name Type | You assign later and want the zero value first |
| var name Type = value | You need a type other than the inferred one (e.g. float64) |
| var name = value | Package-level declarations with a value |
| name := value | The everyday form inside functions |
Every variable declared without a value gets its type's zero value: `0` for number types, `""` for strings, `false` for bool, and `nil` for types such as pointers, slices and maps. You can never read leftover garbage from memory as you can in C. That is why `var total int` followed straight away by `total += price` is perfectly fine.
Do not mix up `:=` and `=`. `:=` declares a new variable and gives it a value; `=` stores a new value in a variable that already exists. The left side of `:=` must contain at least one new variable, or you get `no new variables on left side of :=`.
You can declare or assign several variables at once: `city, students := "Yangon", 40`. The right side is evaluated completely before anything is assigned, so `a, b = b, a` swaps two values without a temporary variable. An unused local variable is a compile error, but the rule does not apply to package-level variables.
Related variables can be declared together in a `var ( ... )` block, which is common at package level: `host = "localhost"` and `port = 8080` on separate lines inside one block. When a statement hands you a value you do not need, assign it to the blank identifier `_`: `_, err := strconv.Atoi(text)` keeps only the error. `_` is not a real variable, so you can never read from it, and it never triggers the 'declared and not used' error.
- Declare it (var or :=)
- It holds a zero or given value
- Assign new values with =
- It goes out of scope at block end
`:=` makes a new box; `=` puts something into a box that already exists.
General pattern: ways to declare variables
var packageLevel = value // outside functions: var only
func f() {
var a Type // zero value
var b Type = value // explicit type
c := value // inferred type, functions only
d, e := value1, value2 // several at once
a = newValue // assignment, not a declaration
}Only `var` works at package level. Inside a function, use `var` when you want a specific type or the zero value, and `:=` for most other cases. The `=` on the last line changes a value; it does not declare anything.
Example: every declaration style in one program
This program uses a package-level variable, a typed `var`, a `var` without a value, `:=` and a multiple declaration. Predict what `lessons` prints the first time.
package main
import "fmt"
var appName = "TaskTracker" // package level: var, never :=
func main() {
var language string = "Go"
var lessons int // no value yet: starts at the zero value 0
version := 1.22
isFast := true
fmt.Println(appName, language, version, isFast)
fmt.Println("lessons before:", lessons)
lessons = 5
lessons = lessons + 1
city, students := "Yangon", 40
fmt.Println("lessons after:", lessons)
fmt.Println(city, students)
}Code breakdown
- Package-level variable
var appName = "TaskTracker" // package level: var, never :=It sits outside any function, so it must use `var`. The type is inferred as string from `"TaskTracker"`, and every function in the package can use it.
- Zero value
var lessons int // no value yet: starts at the zero value 0With no value given, it gets `int`'s zero value, `0`. That is why the first print shows `lessons before: 0` instead of an error.
- Inferred float
version := 1.22A literal with a decimal point makes the compiler infer `float64`. In real code a version you only display, never calculate with, is better stored as the string `"1.22"`.
- Assignment, not declaration
lessons = lessons + 1`lessons` already exists, so this uses `=`. The right side is evaluated first: 5 + 1 = 6. Writing `:=` here would give a `no new variables` error.
- Two variables at once
city, students := "Yangon", 40Two variables are declared on one line. Names and values pair up in order, so `city` is a string and `students` is an int.
TaskTracker Go 1.22 true
lessons before: 0
lessons after: 6
Yangon 40Scope and shadowing
A variable is visible only inside the `{ }` block where it is declared; that region is its scope. If an inner block declares a variable with the same name using `:=`, it creates a brand-new variable that hides the outer one, which is called shadowing. Any change made inside disappears when the block ends.
package main
import "fmt"
func main() {
total := 10
if total > 5 {
total := total * 2 // a NEW variable that hides the outer one
fmt.Println("inside:", total)
}
fmt.Println("outside:", total)
}It prints `inside: 20` and then `outside: 10`. To change the outer `total`, the inner line must use `=`: `total = total * 2`.
In real projects
How variables are used in real Go code
In real Go code most variables inside functions are declared with `:=`, as in `user, err := findUser(id)`. Receiving a value and an error together is the most common use of multiple declaration. Because `:=` still works when `err` already exists, as long as one variable on the left is new, error-checking code stays short.
Zero values are also a design tool. The standard library makes types such as `int` counters and `strings.Builder` usable straight from `var`, with no setup. Package-level variables are used with care: when many goroutines change one at the same time it becomes a race condition, so they are mostly kept for settings and values that never change.
Common mistakes
Common variable mistakes
1. Using := at package level
`count := 0` outside a function gives `non-declaration statement outside function body`. At package level write `var count = 0`, or use `const` for a value that never changes.
2. Redeclaring an existing variable with :=
`total := 1` followed by `total := 2` in the same scope gives `no new variables on left side of :=`. To change the value, use `=`: `total = 2`.
3. Shadowing by accident inside an inner block
When `:=` inside an `if` or `for` block creates a new variable, the compiler says nothing, but the outer value never changes and the bug is hard to find. Every time you write `:=` with an existing name inside a block, ask whether you really want a new variable.
4. Checking a number variable against nil
Expecting an unset variable to be null, as in other languages, people write `var count int` and then `if count == nil`, which is the compile error `mismatched types int and untyped nil`. An int, string or bool can never be nil; it starts at its zero value. If you genuinely need to know whether a value was set, keep a separate `bool` flag, or use a pointer, which a later lesson covers.
Best practices
Best practices
- Use `:=` by default inside functions, and `var x T` when you want the zero value.
- Declare variables close to where they are used instead of piling them at the top of the function.
- Use `const`, not a variable, for values that should never change, such as an app name, a limit or a timeout.
Mini challenge
Mini challenge: a shopping cart tally
Write a program that adds items to a cart twice and works out the item count, the total in kyats and a 5% tax.
- Declare `items` and `total` with `var` and no value, then print their zero values
- Add 2 items (3000 kyats) and then 1 item (1500 kyats), using multiple assignment
- Keep `const taxPercent = 5` at package level and compute the tax with `:=`
- Print the item count, the total and the tax
package main
import "fmt"
// TODO: package-level constant taxPercent
func main() {
// TODO: declare items and total with var (no values)
// TODO: print "start:" and both zero values
// TODO: first purchase: 2 items, 3000 kyats (one multiple assignment)
// TODO: second purchase: 1 item, 1500 kyats
// TODO: tax := ...
// TODO: print items, then total and tax
}Expected: start: 0 0 items: 3 total: 4500 tax: 225
Show hint
`items, total = items+2, total+3000` updates both in one line. For a percentage with integers, multiply before dividing: `total * taxPercent / 100`.
Show solution
package main
import "fmt"
const taxPercent = 5
func main() {
var items int
var total int
fmt.Println("start:", items, total)
items, total = items+2, total+3000
items, total = items+1, total+1500
tax := total * taxPercent / 100
fmt.Println("items:", items)
fmt.Println("total:", total, "tax:", tax)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Only var works at package level; := is the everyday form inside functions.
- Every variable without a value starts at its zero value: 0, "", false or nil.
- := declares new variables and = changes existing ones; := needs at least one new name on its left.
- Reusing a name with := in an inner block shadows the outer variable, which stays unchanged.
A Tour of Go — Go