Course › Week 1 · Basics and a first CLI › Day 2 · lesson 2 of 42 · 20 min reading + 45–60 min practice
Variables, types and zero values
One fixed type per variable, a zero value instead of null, conversions on purpose, and if and for.
On this page
In PHP a variable holds anything, and its type can change from one line to the next. In Go a variable has one type, decided when it is created, for its whole life. The compiler checks every use against it.
Today: the two ways to create a variable, the basic types, what a variable holds before you set it, how to convert between types, constants, and if and for.
Creating variables
1. var
The long form names the variable, then its type, then the value: var name type = value.
package main
import "fmt"
func main() {
var guest string = "Astrid"
var nights int = 3
fmt.Println(guest, "stays", nights, "nights")
}
Astrid stays 3 nightsThe type comes after the name. It reads left to right: “variable guest, a string, set to Astrid”. Every declaration in Go follows that order, function parameters too.
2. := declares and sets
Inside a function you usually write := instead. Go takes the type from the value on the right.
package main
import "fmt"
func main() {
guest := "Astrid"
nights := 3
price := 129.50
fmt.Printf("%s: %d nights at %.2f\n", guest, nights, price)
fmt.Printf("types: %T, %T, %T\n", guest, nights, price)
}
Astrid: 3 nights at 129.50
types: string, int, float64%T prints a value’s type, and %.2f prints a decimal number with two digits after the point. 3 became an int and 129.50 a float64, the default type for a whole number and for a decimal one.
:= creates a new variable. To change an existing one, use plain =: nights = 4. := works only inside functions; at the top of a file, outside any function, you must write var.
3. A variable keeps its type
Once nights is an int, it holds whole numbers and nothing else:
package main
import "fmt"
func main() {
nights := 3
nights = "four"
fmt.Println(nights)
}
# hello
./main.go:7:11: cannot use "four" (untyped string constant) as int value in assignmentPHP would accept this and change the variable’s type to string. Go stops at the line: "four" is a string, and nights is an int. “Untyped string constant” is how the compiler names a string literal that has not been given a type yet.
4. Every variable must be used
Like the unused import in the first lesson, a variable you create and never read is an error:
package main
import "fmt"
func main() {
nights := 3
total := nights * 129
fmt.Println(nights, "nights")
}
# hello
./main.go:7:2: declared and not used: totalMost of the time it means a bug: you computed something and forgot to use it. Delete the line, or use the variable.
The basic types
| Type | Holds | Example |
|---|---|---|
int | A whole number, 64 bits on any modern machine | nights := 3 |
float64 | A decimal number | rating := 4.5 |
string | Text, as UTF-8 bytes, and immutable | name := "Astrid" |
bool | true or false | paid := false |
int64, int32, uint8… | Whole numbers of a fixed size, for files, protocols and databases | var id int64 = 42 |
Use int for counting and float64 for measuring, unless a file format or a database column asks for an exact size. byte is another name for uint8, and you will see it whenever Go reads raw data.
Money is never a float64: 0.1 + 0.2 is not exactly 0.3 in binary, in Go or in PHP. Keep money as whole cents in an int64, the way you would store it in a database column.
Zero values
5. A variable you never set is zero, not null
A var with no value gets its type’s zero value: 0 for numbers, "" for strings, false for booleans.
package main
import "fmt"
func main() {
var nights int
var rating float64
var guest string
var paid bool
fmt.Printf("nights=%d rating=%v guest=%q paid=%t\n", nights, rating, guest, paid)
}
nights=0 rating=0 guest="" paid=false%q prints a string in quotes, so an empty one is visible, and %t prints a boolean. There is no “undefined” and no “uninitialised” in Go: every variable always holds a valid value of its type.
That replaces a lot of PHP’s null checks. A counter starts at 0, a string you build starts as "", and code that adds to them just works. Where “no value” must be different from zero (a guest count that was never given is not zero guests), Go has other tools, covered when you need them.
Converting between types
6. No automatic conversion
PHP converts numbers silently. Go never does, not even from int to float64:
package main
import "fmt"
func main() {
total := 387.0
nights := 3
fmt.Println(total / nights)
}
# hello
./main.go:9:14: invalid operation: total / nights (mismatched types float64 and int)Both sides of / must have the same type. Go will not guess which one you meant, because each choice gives a different answer.
7. Convert on purpose
You convert with the type’s name, like a function call: float64(nights).
package main
import "fmt"
func main() {
total := 387.0
nights := 3
guests := 2
perNight := total / float64(nights)
perGuest := nights / guests
fmt.Printf("per night: %.2f\n", perNight)
fmt.Println("nights per guest:", perGuest)
}
per night: 129.00
nights per guest: 1Watch the second line: 3 / 2 between two ints is 1, not 1.5. Dividing whole numbers drops the remainder, like PHP’s intdiv(). float64(3) / float64(2) gives 1.5.
Converting a float64 to an int drops the decimals: int(2.9) is 2. Text to a number is different, because the text may not be a number at all; that comes with errors in the next lesson.
Constants
8. const
A value that never changes is a const. It is fixed at compile time; assigning to it later is an error.
package main
import "fmt"
const maxGuests = 6
const cleaningFeeCents = 4500
func main() {
nights := 3
nightlyCents := 12950
totalCents := nights*nightlyCents + cleaningFeeCents
fmt.Println("max guests:", maxGuests)
fmt.Println("total in cents:", totalCents)
}
max guests: 6
total in cents: 43350Constants can live at the top of the file, outside any function, like PHP’s const in a class. A constant written as a plain number has no fixed type until it is used, which is why maxGuests works with an int here and would work with a float64 elsewhere.
Names start lowercase here. In Go, a capital first letter means “visible outside this package”, like public. Week 2 covers it; until then, lowercase names.
if and for
9. if
No parentheses around the condition, and the braces are always required, even for one line.
package main
import "fmt"
func main() {
guests := 7
maxGuests := 6
if guests > maxGuests {
fmt.Println("too many guests:", guests)
} else if guests == maxGuests {
fmt.Println("full house")
} else {
fmt.Println("room for", maxGuests-guests, "more")
}
}
too many guests: 7The condition must be a bool. PHP’s if ($count) works because PHP treats 0 as false; in Go, if guests does not compile. Write the comparison: if guests > 0.
10. for is the only loop
Go has no while and no do. for does all of it, in three shapes.
package main
import "fmt"
func main() {
// Like PHP's for: start; condition; step.
for night := 1; night <= 3; night++ {
fmt.Println("night", night)
}
// Only a condition: PHP's while.
balance := 100
for balance > 0 {
balance -= 40
}
fmt.Println("balance:", balance)
// No condition at all: forever, until break.
attempt := 0
for {
attempt++
if attempt == 3 {
break
}
}
fmt.Println("attempts:", attempt)
}
night 1
night 2
night 3
balance: -20
attempts: 3// starts a comment, as in PHP. night++ adds one; in Go it is a statement on its own line, never part of an expression like $a = $i++.
continue skips to the next round and break leaves the loop, as in PHP. Looping over a list has its own form, range, in the slices lesson.
Coming from PHP
<?php
$nights = 3;
$nights = "four"; // fine: $nights is now a string
$total = 387.0 / $nights; // a TypeError in PHP 8, at runtime
$guest; // undefined: null, and a warning when read
if ($count) { } // 0, "" and [] are all false
In Go every one of these lines is a compile error, found before the program ever runs. The honest cost: you write float64(nights) where PHP converted for you, and you think about types up front.
declare(strict_types=1) and type declarations move PHP part of the way, but only for function parameters and properties, and only at runtime. A Go variable’s type is checked at every use, at compile time.
PracticeA Tour of Go: variables to constants, for and if, one small program
In A Tour of Go, do the basics pages from Variables to Numeric Constants, then the flow control pages from For to If and else. Skip the exercise on page 8 for now; it uses functions, which come next.
Exercise: a price breakdown
A stay costs 12,950 cents a night for 4 nights, plus a 4,500-cent cleaning fee, split between 3 guests. Print the total, then each guest’s share in cents, then what is left over after splitting in whole cents (% gives the remainder). Use a const for the cleaning fee. Then print the share as a decimal amount of euros with two digits.
Show the solution
package main
import "fmt"
const cleaningFeeCents = 4500
func main() {
nights := 4
nightlyCents := 12950
guests := 3
totalCents := nights*nightlyCents + cleaningFeeCents
shareCents := totalCents / guests
leftoverCents := totalCents % guests
fmt.Println("total:", totalCents)
fmt.Println("each guest:", shareCents)
fmt.Println("left over:", leftoverCents)
fmt.Printf("each guest: %.2f EUR\n", float64(shareCents)/100)
}
total: 56300
each guest: 18766
left over: 2
each guest: 187.66 EURRemember
- A variable’s type never changes; convert on purpose with
float64(n), towards the type that keeps the information. - An unset variable is its zero value (
0,"",false), never null. - Money is whole cents in an integer, never a
float64.
Tomorrow: functions that return two values, and errors that are ordinary values you check.