Beginner · Getting started with Go · topic 4 of 46 · 35 min
Variables, basic types and zero values
Explanation
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.
Two ways to declare
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)
}- 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
| Type | Holds | Example |
|---|---|---|
| int | whole numbers (64 bits on 64-bit computers) | marks := 452 |
| int8, int16, int32, int64 | whole numbers of a fixed size | var b int8 = 100 |
| uint, uint8 ... uint64 | whole numbers that cannot be negative | var age uint8 = 21 |
| float64 (and float32) | decimal numbers | rate := 7.25 |
| string | text (UTF-8 bytes) | city := "Kochi" |
| bool | true or false | paid := true |
| byte | another name for uint8 (one byte) | var b byte = 'A' |
| rune | another name for int32 (one Unicode character) | r := '₹' |
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.
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)Several at once
a, b := 10, 20
a, b = b, a // swap in one line
name, age := "Asha", 21
fmt.Println(a, b, name, age)Integer and float maths
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)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.
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 changedNeed 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 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.
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)
}Practice (0/4 done)
What does this print? var city string var marks int fmt.Println(marks, city == "")
What does this print? fmt.Println(17 / 5, 17 % 5)
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)
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Constants, iota and type conversionsGetting started with Go · same module
- Installing Go and the go commandGetting started with Go · same module
- Types and variablesC# and .NET · Getting started with C# and .NET
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Your first Dart program, variables and typesFlutter and Dart · Dart basics
- Variables: giving names to valuesPython Programming · First steps in Python
Questions people ask about this
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
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.
Which keyword is for a value fixed at compile time?Related
Answer: const
const values are known while compiling.
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.
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 more topic in “Getting started with Go” before its exam: Constants, iota and type conversions.
- Module 1 exam: Getting started with Go · 14 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Control flow and functions. 46 topics left in the course before the final exam.