These are the notes for Go episode 3. You will learn why variables exist, how to declare them with var and :=, how Go infers types, what zero values are, how to declare several variables and swap them in one line, why Go refuses unused variables and how the blank identifier _ helps, and where a variable can be used (scope), including the sneaky bug called shadowing. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).
The problem: the chai price changed
Sharma ji's masala chai costs Rs 10, and that 10 is written in many places. Milk gets costlier, the price becomes 12, and on a busy morning one place is missed. A customer gets a wrong bill.
package main
import "fmt"
func main() {
fmt.Println("Masala chai:", 12, "rupees")
fmt.Println("2 cups:", 2*12)
fmt.Println("5 cups:", 5*10)
}
Masala chai: 12 rupees
2 cups: 24
5 cups: 50
Five cups should be 60. No error, just a wrong answer. Why: the same value was copied into many places, so one change must be made in many places. (* means multiply.)
The fix: a variable, a labelled dabba
| In a kitchen | In Go |
|---|---|
| A steel dabba that holds something | a variable: a named place in memory that holds a value |
| Its label, "price" | the variable's name |
| Only sugar goes in the sugar dabba | its type: what kind of value may go in |
package main
import "fmt"
func main() {
var price int = 12
fmt.Println("Masala chai:", price, "rupees")
fmt.Println("2 cups:", 2*price)
fmt.Println("5 cups:", 5*price)
}
Masala chai: 12 rupees
2 cups: 24
5 cups: 60
Change the price in one place and every line follows.
Anatomy of var price int = 12
| Piece | Meaning |
|---|---|
var |
"I'm creating a new variable" (declaring it) |
price |
its name. Go style: short, clear names; several words in camelCase (cupCount) |
int |
its type: an integer, a whole number |
= 12 |
assignment: put this value in. = does not mean "is equal to" |
The type is enforced
var price int = 12
price = "twelve"
./main.go:7:13: cannot use "twelve" (untyped string constant) as int value in assignment
A variable's type never changes. Go checks this before the program runs.
Type inference and the short declaration :=
var price int = 12 // type written
var price = 12 // type inferred: int
price := 12 // short variable declaration
- Type inference: when you give a value, Go works out the type from it.
:=declares and assigns in one step. It is the most common way to create a variable inside a function.- Rules:
:=works only inside functions and only when at least one name on the left is new. Use plain=to change an existing variable.
var price = 12
rate := 4.5
fmt.Printf("%T %T\n", price, rate)
int float64
%T prints a value's type. float64 is a number with a fractional part (a decimal point). Number types are episode 4.
:= mistakes
price := 12
price := 15
./main.go:7:11: no new variables on left side of :=
package main
import "fmt"
city := "Pune"
func main() {
fmt.Println(city)
}
./main.go:5:1: syntax error: non-declaration statement outside function body
Outside functions, only declarations that start with a keyword (like var city = "Pune") are allowed.
Zero values: a new notebook page is blank
A variable declared without a value starts at its type's zero value: never random leftover data.
var cups int
var name string
var paid bool
var rate float64
fmt.Println(cups, name, paid, rate)
fmt.Printf("%d %q %t %v\n",
cups, name, paid, rate)
0 false 0
0 "" false 0
| Type | Zero value |
|---|---|
int (and every integer type) |
0 |
float64 |
0 |
string |
"" (the empty string) |
bool |
false |
- A bool (boolean) is a yes-or-no value:
trueorfalse. %qprints a string inside quotes, so the empty string becomes visible as"".%d= integer,%t= bool,%v= any value in its default format.- A long call can be split across lines after a comma.
Several variables at once
var a, b int = 1, 2
var c, d = "chai", 3.5
x, y := 10, 20
fmt.Println(a, b, c, d, x, y)
1 2 chai 3.5 10 20
Values are matched to names in order, left to right (multiple assignment).
Swapping: the two-glasses puzzle
Glass A has milk, glass B has juice. Pour B into A, and A's milk is gone.
milk, juice := "milk", "juice"
milk = juice
juice = milk
fmt.Println(milk, juice)
juice juice
Go evaluates all the right-hand values first, then assigns them, so it swaps without a third glass:
milk, juice := "milk", "juice"
milk, juice = juice, milk
fmt.Println(milk, juice)
juice milk
Unused variables and the blank identifier _
strconv.Atoi ("ASCII to integer", from the strconv package) converts text like "42" into the int 42. It returns two values: the number, and an error value that says whether the conversion failed.
package main
import (
"fmt"
"strconv"
)
func main() {
cups, err := strconv.Atoi("42")
fmt.Println(cups)
}
./main.go:9:11: declared and not used: err
In Go, a variable you create and never use is an error (like an unused import): it is almost always a bug.
The blank identifier _ is the dustbin: anything assigned to it is thrown away, on purpose.
cups, _ := strconv.Atoi("42")
fmt.Println(cups + 1)
43
Ignore errors only when you are sure the value is valid. The errors episodes show how to check err.
Scope: which room can see it
| A school | Go |
|---|---|
| A classroom whiteboard, seen only in that room | block scope: a variable declared inside { } lives only there |
| The school notice board, read by every class | package scope: declared outside all functions, visible to every function in the package |
A block is code between a pair of curly braces. Scope is the part of the code where a name can be used.
package main
import "fmt"
func main() {
{
msg := "inside"
fmt.Println(msg)
}
fmt.Println(msg)
}
./main.go:10:17: undefined: msg
package main
import "fmt"
var shop = "Sharma Chai"
func main() {
fmt.Println("Welcome to", shop)
printBill()
}
func printBill() {
fmt.Println("Bill from", shop)
}
Welcome to Sharma Chai
Bill from Sharma Chai
printBill is a second function we wrote; printBill() calls it (functions are episode 9). Keep package-level variables rare: any function can change them.
Shadowing: two people named Rahul
When a new Rahul joins your class, calling "Rahul!" inside the class reaches the new one; the outer Rahul still exists but is hidden. A variable declared in an inner block with the same name as an outer one shadows (hides) it.
total := 0
{
total := 50
fmt.Println("inside:", total)
}
fmt.Println("outside:", total)
inside: 50
outside: 0
:= created a new total inside the block. The outer one never changed, and there is no error. Fix: use = to change the existing variable.
total := 0
{
total = 50
fmt.Println("inside:", total)
}
fmt.Println("outside:", total)
inside: 50
outside: 50
When a value mysteriously doesn't change, look for a := that should be =.
Common mistakes (and the real error messages)
| You wrote | Real error | Fix |
|---|---|---|
price = "twelve" (price is int) |
cannot use "twelve" (untyped string constant) as int value in assignment |
assign an int: price = 15 |
price := 15 when price exists |
no new variables on left side of := |
price = 15 |
city := "Pune" outside a function |
syntax error: non-declaration statement outside function body |
var city = "Pune" |
cups, err := strconv.Atoi("42"), err unused |
declared and not used: err |
use err, or cups, _ := ... |
using msg after its block ends |
undefined: msg |
declare it before the block |
total := 50 inside a block |
no error: the outer total is unchanged |
total = 50 |
a = b; b = a to swap |
no error: both get the same value | a, b = b, a |
Mini project: the chai bill
package main
import "fmt"
func main() {
// Mini project: the chai bill
price := 12
cups := 3
total := price * cups
fmt.Printf("%d cups x Rs %d = Rs %d\n",
cups, price, total)
}
3 cups x Rs 12 = Rs 36
Each %d is replaced by the next value, in order.
Practice
- Declare
name,ageandcitywith:=and print them in onePrintln. - Print the zero values of
int,string,boolandfloat64using%vand%q. - Swap two ints
a := 5andb := 9, print them, then swap them back. - Predict the output, then run:
x := 1
{
x = 5
y := x * 2
fmt.Println(x, y)
}
fmt.Println(x)
Solutions and hints
name, age, city := "Aarav", 21, "Pune"thenfmt.Println(name, age, city)printsAarav 21 Pune.var i int; var s string; var b bool; var f float64; fmt.Printf("%v %q %v %v\n", i, s, b, f)prints0 "" false 0.a, b = b, aprints9 5; doing it again gives5 9.5 10then5.x = 5changes the outerx(no shadowing);yexists only inside the block.
Quick quiz
What does this print (inside main)?
x := 1
{
x := 2
x = x + 1
}
fmt.Println(x)
- A.
1 - B.
2 - C.
3 - D. Compile error
Answer
A. The inner x := 2 is a new variable that shadows the outer x; only the inner one becomes 3. Outside the block, x is still 1.
Interview questions
- What is the difference between
var x = 5andx := 5? Where can each be used? - What are zero values? What is the zero value of
int,string,bool,float64? - Why does Go reject unused variables and imports?
- What is the blank identifier and when would you use it?
- How do you swap two variables in Go? Why does
a, b = b, awork? - What is variable shadowing? Show a bug it causes.
- What is the difference between block scope and package scope?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Variable | a named place in memory that holds a value | price |
| Declare | create a variable (and its type) | var price int |
| var | the keyword that declares a variable | var price int = 12 |
| Type | what kind of value a variable may hold | int, string |
| int / integer | a whole number | 12 |
| float64 | a number with a fractional part | 4.5 |
| string | text | "Pune" |
| bool | true or false |
var paid bool |
| Assignment | putting a value into a variable with = |
price = 15 |
| camelCase | joining words, each later word capitalised | cupCount |
| Type inference | Go works out the type from the value | var price = 12 → int |
| Short variable declaration | :=, declare and assign inside a function |
price := 12 |
| Zero value | the starting value of a variable given no value | 0, "", false |
| Empty string | a string with no characters | "" |
| Multiple assignment | several names and values in one statement | x, y := 10, 20 |
| Swap | exchange two variables' values | a, b = b, a |
| strconv.Atoi | converts a string to an int, returning (int, error) | strconv.Atoi("42") |
| Return value | a value a function gives back | 42 and err |
| error | a value describing what went wrong (or nil if nothing did) |
err |
| Unused variable error | declared and not used: x |
an unused err |
| Blank identifier | _, throws a value away on purpose |
cups, _ := ... |
| Block | code between { and } |
{ msg := "hi" } |
| Scope | the part of the code where a name can be used | |
| Block scope | visible only inside its block | msg inside { } |
| Package scope | declared outside functions, visible in the whole package | var shop = "..." |
| Shadowing | an inner variable with the same name hides an outer one | inner total := 50 |
| %T, %d, %q, %t, %v | Printf verbs: type, integer, quoted string, bool, any value | Printf("%T", x) |
Summary
- A variable is a named, typed box. Write a value once, use it everywhere.
var name type = value; let Go infer the type withvar name = value; use:=inside functions.:=creates,=changes.:=only inside functions and only with at least one new name.- Every type has a zero value:
0,"",false. a, b = b, aswaps._throws a value away. Unused variables are errors.- Block scope vs package scope; beware shadowing with
:=in inner blocks.
Next episode: basic types and conversions. A visitor counter suddenly goes negative, and you meet Go's integer sizes, overflow, floats, byte, rune and explicit conversion.