Skip to content

Beginner · Getting started with Go · topic 4 of 46 · 35 min

Variables, basic types and zero values

Explanation

A variable is a named box that holds a value of one fixed type, such as int, float64, string or bool. You declare it with var, or with := inside functions. A variable you do not set gets its zero value (0, "", false), and a local variable you never use is a compile error.

What a variable is

A variable is a name for a value your program keeps in memory, such as a price or a student's name. In Go every variable has a type, and the type never changes. A type says what kind of value fits: whole numbers, decimal numbers, text or true/false.

Think of it like this: Variables are like labelled steel tiffin boxes. A box labelled "dal" only ever holds dal. You can change which dal is inside, but you cannot put rotis in the dal box. Go checks the labels before the program even runs.

Two ways to declare

go
package main

import "fmt"

var shopName = "Sharma Stores" // package level: must use var

func main() {
	var price int = 499    // full form: var name type = value
	var qty = 3            // type inferred as int
	total := price * qty   // short form, only inside functions
	var discount int       // no value: gets the zero value 0
	fmt.Println(shopName, total, discount)
}
Prints Sharma Stores 1497 0.
  • var name type = value: the full form. Works everywhere.
  • var name = value: Go infers (works out) the type from the value.
  • name := value: the short variable declaration. Only inside functions. It is what you will write most often.
  • Assignment with = changes an existing variable: total = 2000. := creates a new one.

Basic types

TypeHoldsExample
intwhole numbers (64 bits on 64-bit computers)marks := 452
int8, int16, int32, int64whole numbers of a fixed sizevar b int8 = 100
uint, uint8 ... uint64whole numbers that cannot be negativevar age uint8 = 21
float64 (and float32)decimal numbersrate := 7.25
stringtext (UTF-8 bytes)city := "Kochi"
booltrue or falsepaid := true
byteanother name for uint8 (one byte)var b byte = 'A'
runeanother name for int32 (one Unicode character)r := '₹'
Tip: Use int for whole numbers and float64 for decimals unless you have a clear reason. Use the sized types (int32, int64) when a file format, database column or API demands them.

Zero values: no garbage, ever

In C, a variable you forget to set may hold random leftover memory. In Go every variable starts with its zero value, so it is always safe to read.

go
var n int        // 0
var f float64    // 0
var s string     // "" (empty string)
var ok bool      // false
var p *int       // nil (no pointer)
var list []int   // nil slice, length 0
fmt.Println(n, f, s == "", ok, p, list)
Prints 0 0 true false <nil> []. nil means "nothing here" for pointers, slices, maps, channels, functions and interfaces.

Several at once

go
a, b := 10, 20
a, b = b, a            // swap in one line
name, age := "Asha", 21
fmt.Println(a, b, name, age)
Prints 20 10 Asha 21.

Integer and float maths

go
fmt.Println(7 / 2)     // 3   (int / int drops the fraction)
fmt.Println(7 % 2)     // 1   (remainder)
fmt.Println(7.0 / 2)   // 3.5 (a float is involved)

var small int8 = 127
small++
fmt.Println(small)     // -128 (it wrapped around)
Integer division truncates. Fixed-size integers wrap around silently at run time when they overflow.
Careful: Money: do not store rupees as float64 in serious code. 0.1 + 0.2 is not exactly 0.3 in floating point. Store paise as int64 (₹499.50 is 49950 paise) and format at the end.

The rules that surprise beginners

  • A local variable that is declared but never used is a compile error: "declared and not used: x". Delete it, or use it.
  • If you really must ignore a value, assign it to the blank identifier _ (underscore): _ = x.
  • := needs at least one NEW variable on the left. x := 1 then x := 2 in the same scope fails with "no new variables on left side of :=". Use x = 2.
  • Shadowing: := inside an if or for block makes a NEW variable that hides the outer one. Changes to it do not change the outer one.
  • := cannot be used outside functions. At package level, write var.
go
count := 0
if true {
	count := 5        // a new, inner count (shadows the outer one)
	fmt.Println(count) // 5
}
fmt.Println(count)    // 0, the outer count was never changed
A classic bug. go vet with the shadow analyzer, or careful reading, catches it. Use = when you mean to change the outer variable.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Variables, basic types and zero values · 1/7

Variables and types

Variables are named boxes for values. In Go, each box has a type that never changes.

Prefer a video by a teacher? Find free videos on “golang variables types zero values short declaration tutorial” on YouTube ↗

In real life: Recording a student's marks

A school result system stores each student's roll number, name, total marks and a pass flag. Using int for marks and bool for pass keeps the data honest: nobody can accidentally store "ninety" as marks, because the compiler rejects it before the program runs.

go
package main

import "fmt"

func main() {
	roll := 23
	name := "Meena"
	total := 412
	maxMarks := 500
	passed := total >= 165

	percent := float64(total) * 100 / float64(maxMarks)
	fmt.Printf("%d %s %d/%d %.1f%% passed=%t\n", roll, name, total, maxMarks, percent, passed)
}
Prints 23 Meena 412/500 82.4% passed=true. %t prints a bool.

Practice (0/4 done)

Task 1 · Question

What does this print? var city string var marks int fmt.Println(marks, city == "")

Task 2 · Question

What does this print? fmt.Println(17 / 5, 17 % 5)

Task 3 · Question

Which line is the bug? 1: total := 0 2: for _, p := range []int{10, 20} { 3: total := total + p 4: _ = total 5: } 6: fmt.Println(total)

Task 4 · Practice

Write a program that stores a product price in paise as an int (for example 49950 for ₹499.50), a quantity, and prints the total in rupees with two decimals using integer maths only.

Quick quiz

Question 1

1.Where can you use := ?

Question 2

2.What is the zero value of a bool?

Question 3

3.x := 1 and then x := 2 on the next line in the same block. What happens?

Question 4

4.Which type is another name for int32 and holds one Unicode character?

Question 5

5.Why store money as int64 paise instead of float64 rupees?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Where can you use := ?

Answer: Only inside functions

The short declaration works only inside function bodies; package-level variables need var.

What is the zero value of a bool?

Answer: false

Every bool starts as false.

x := 1 and then x := 2 on the next line in the same block. What happens?

Answer: Compile error: no new variables on left side of :=

:= must declare at least one new variable. To change x, write x = 2.

Which type is another name for int32 and holds one Unicode character?

Answer: rune

rune is an alias for int32 and represents a Unicode code point.

Why store money as int64 paise instead of float64 rupees?

Answer: Floating point cannot store values like 0.1 exactly, so sums drift

Binary floating point gives tiny rounding errors; whole paise in an integer are exact.

Which type holds true or false?Related

Answer: bool

bool has exactly two values: true and false.

From Types and variables

What is in an int variable declared inside main with int n; and no value?Related

Answer: Garbage: reading it is undefined behaviour

Local variables are not set to zero automatically. Always initialise them.

From Variables, types and constants

Which keyword is for a value fixed at compile time?Related

Answer: const

const values are known while compiling.

From Your first Dart program, variables and types

Which is a valid variable name?Related

Answer: total_marks

Names cannot start with a digit, cannot contain spaces, and cannot be keywords like class.

From Variables: giving names to values

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Getting started with Go” before its exam: Constants, iota and type conversions.
  2. Module 1 exam: Getting started with Go · 14 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Control flow and functions. 46 topics left in the course before the final exam.

← Previous: Your first program and Go modules