Few constructs, used everywhere
Go has one loop keyword (for), one conditional (if) and one multi-way branch (switch). There is no while, no do, no ternary ?: operator. This is deliberate: when there is only one way to write a loop, every Go programmer reads every loop the same way, and code written by a colleague on another continent looks like code you wrote yourself.
The type system is similarly plain but strict. Every variable has a type fixed at compile time, the compiler infers it where it can, and nothing converts automatically: adding an int to a float64, or even an int32 to an int64, requires you to say so. That strictness catches real mistakes (a duration in seconds added to one in milliseconds, say) at the cost of a few extra characters.
Two features soften the strictness. Zero values mean that every variable starts with a sensible value (0, "", false, nil), so there is no such thing as an uninitialised variable. And untyped constants let you write x * 2 or price * 1.2 without casts, because a literal takes on whatever type the context needs.
Variables, zero values and constants
Definition— declarations
var name Type = value declares a variable; either the type or the value may be left out (if the value is omitted, the variable holds its type's zero value). Inside functions, name := value is the short form, inferring the type. const Name = value declares a constant whose value is known at compile time; a constant written without a type is untyped and takes its type from the context where it is used. In a const block, iota stands for 0, 1, 2, ... on successive lines.
package main
import "fmt"
// Constants can be untyped: they take a type only when used.
const Pi = 3.14159265358979
// iota counts up within a const block: a compact way to define enumerations.
type Weekday int
const (
Monday Weekday = iota + 1
Tuesday
Wednesday
)
const (
_ = iota // skip zero
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)
func main() {
// Three ways to declare a variable.
var guests int = 4
var host = "Mariam" // type inferred: string
cups := guests + 1 // short declaration, inside functions only
// Every type has a zero value; there are no uninitialised variables.
var count int
var price float64
var name string
var ready bool
fmt.Printf("%d %v %q %v\n", count, price, name, ready)
fmt.Println(host, "makes", cups, "cups")
// Several at once, and swapping without a temporary.
a, b := 1, 2
a, b = b, a
fmt.Println(a, b)
fmt.Println(Tuesday, Wednesday, KB, MB, GB)
var area float32 = Pi * 2 * 2 // the untyped constant becomes a float32 here
fmt.Printf("%.4f %T\n", area, area)
}0 0 "" false
Mariam makes 5 cups
2 1
2 3 1024 1048576 1073741824
12.5664 float32Points to notice:
- The zero values are 0 for numbers,
""for strings andfalsefor booleans; pointers, slices, maps, channels, functions and interfaces start asnil. Idiomatic Go designs types so that the zero value is useful as it is: an emptystrings.Builderorsync.Mutexis ready to use without any constructor. :=declares new variables and works only inside functions. At package level, usevar. Mixing=and:=up is a classic early mistake:=assigns to a variable that already exists.a, b = b, aswaps two values. The right-hand side is evaluated completely before anything is assigned.iotaproduces enumerations.Weekdayis a new type whose underlying type isint, andMonday,Tuesday,Wednesdayare 1, 2 and 3. In the second block, each line repeats the previous expression withiotaone higher, giving powers of 1024. The blank identifier_throws away the first value.- The untyped constant
Pibecame afloat32because it was used in afloat32expression. HadPibeen declaredconst Pi float64 = ..., assigning it to afloat32would be a compile error.
Numbers, strings and conversions
Go's basic types:
| Type | Notes |
|---|---|
int, uint | the natural size for the machine: 64 bits on all common platforms today |
int8 ... int64, uint8 ... uint64 | fixed sizes, for file formats, protocols and hardware |
byte | another name for uint8 |
rune | another name for int32: one Unicode code point |
float32, float64 | IEEE 754 floating point; float64 is the default |
complex64, complex128 | complex numbers, built in |
string | an immutable sequence of bytes, by convention UTF-8 text |
bool | true or false |
Use int unless you have a reason not to; the standard library does.
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
// Integer sizes: int is 64 bits on 64-bit machines; byte = uint8; rune = int32.
fmt.Println(math.MaxInt8, math.MaxUint8, math.MaxInt)
var level uint8 = 250
level += 10 // overflow wraps around silently, modulo 2^8
fmt.Println("level:", level)
// Division truncates toward zero; % takes the sign of the left operand.
fmt.Println(7/2, -7/2, -7%2, 7.0/2)
// Floating point is IEEE 754, as everywhere.
fmt.Println(0.1+0.2 == 0.3, math.Abs(0.1+0.2-0.3) < 1e-9)
x, y := 0.1, 0.2
fmt.Println(x+y, math.Sqrt(2), math.Inf(1))
// Conversions are always explicit.
n := 42
f := float64(n) / 5
back := int(f) // truncates toward zero
g := -2.7
fmt.Println(f, back, int(g))
small := int8(n * 4) // keeps the low 8 bits: 168 becomes -88
fmt.Println(small)
// Numbers and text: strconv, not string(n).
s := strconv.Itoa(n) + "!"
parsed, err := strconv.Atoi("123")
fmt.Println(s, parsed+1, err)
_, err = strconv.Atoi("12x")
fmt.Println(err)
}127 255 9223372036854775807
level: 4
3 -3 -1 3.5
true true
0.30000000000000004 1.4142135623730951 +Inf
8.4 8 -2
-88
42! 124 <nil>
strconv.Atoi: parsing "12x": invalid syntaxSeveral of these lines deserve a pause:
- Integer overflow wraps silently. 250 + 10 in a
uint8is 4, with no error and no panic, in every build. That is the C behaviour, chosen for speed. When overflow is possible and matters (money, sizes from untrusted input), check before you add, or usemath/bigfor arbitrary precision. - Integer division truncates toward zero, so
-7/2is −3 and-7%2is −1, exactly as in C, Java and Rust (Python differs). 0.1+0.2 == 0.3istruehere, which surprises programmers from every other language. All three are untyped constants, which the compiler evaluates exactly, with arbitrary precision, before converting the result to afloat64. With variables (x+y) the arithmetic happens infloat64at run time, and you get the familiar0.30000000000000004. Compare floats computed at run time with a tolerance.- Conversions are explicit and written like function calls:
float64(n),int(g). Converting a float to an integer truncates toward zero; converting to a smaller integer keeps the low bits (168 becomes −88 in anint8). Converting a constant that doesn't fit is a compile error:int(-2.7)with a literal is rejected, because the compiler can see the value would be lost. - Numbers to text go through the
strconvpackage:ItoaandAtoifor integers,ParseFloat,FormatFloat,Quoteand others. Note thatAtoireturns two values, the number and an error; that pattern is the subject of lesson 6.string(65)does not produce"65"(it produces"A", the character with that code point), andgo vetwarns if you write it.
Note
Go has a short list of built-in functions that need no import: len and cap (sizes), append, copy, make, delete and clear (for slices and maps, lesson 4), new (allocate a variable and return a pointer to it; since Go 1.26, new(42) also sets its initial value), min and max (since Go 1.21, for any ordered values), panic and recover (lesson 6), and complex, real and imag for complex numbers. Everything else lives in a package.
if, for and switch
package main
import (
"fmt"
"strconv"
)
func classify(t int) string {
switch {
case t < 0:
return "freezing"
case t < 15:
return "cold"
case t < 25:
return "mild"
default:
return "hot"
}
}
func main() {
// if can start with a short statement; its variables live only in the if/else.
if n, err := strconv.Atoi("37"); err == nil && n > 30 {
fmt.Println(n, "is", classify(n))
} else if err != nil {
fmt.Println("not a number")
}
// The three-part for loop.
var evens []int
for i := 0; i < 10; i += 2 {
evens = append(evens, i)
}
fmt.Println(evens)
// for as a while loop.
steps, n := 0, 27
for n != 1 {
if n%2 == 0 {
n /= 2
} else {
n = 3*n + 1
}
steps++
}
fmt.Println("Collatz steps for 27:", steps)
// range over an integer (Go 1.22+) and over a slice.
var squares []int
for i := range 4 {
squares = append(squares, i*i)
}
fmt.Println(squares)
for i, t := range []int{-4, 9, 21, 33} {
fmt.Printf("reading %d: %d is %s\n", i, t, classify(t))
}
// switch on a value: cases don't fall through, and can list several values.
for _, day := range []string{"Sat", "Tue", "Fri"} {
switch day {
case "Sat", "Sun":
fmt.Println(day, "weekend")
case "Fri":
fmt.Println(day, "almost weekend")
default:
fmt.Println(day, "weekday")
}
}
// A labelled break leaves the outer loop.
grid := [][]int{{3, 8, 1}, {9, 4, 7}, {2, 6, 5}}
search:
for r, row := range grid {
for c, v := range row {
if v == 7 {
fmt.Println("found 7 at", r, c)
break search
}
}
}
}37 is hot
[0 2 4 6 8]
Collatz steps for 27: 111
[0 1 4 9]
reading 0: -4 is freezing
reading 1: 9 is cold
reading 2: 21 is mild
reading 3: 33 is hot
Sat weekend
Tue weekday
Fri almost weekend
found 7 at 1 2The rules:
- No parentheses, mandatory braces.
if x > 3 {is the only form;if (x > 3) doSomething()doesn't compile. Conditions must bebool; there is no truthiness. ifwith an init statement.if n, err := strconv.Atoi("37"); err == nil && n > 30 {runs the statement first, then tests the condition.nanderrexist only inside theifand itselsebranches. This is the standard shape for "call something, then check its result".forhas four forms. The three-part C formfor init; condition; post {}; the condition-only formfor condition {}, which is Go'swhile; the barefor {}, an infinite loop ended withbreakorreturn; andfor ... range, which iterates over integers (since Go 1.22), slices, arrays, strings, maps, channels and iterator functions. With a slice,rangegives the index and a copy of the element; writefor _, v := range sto ignore the index, orfor i := range sto take only the index.- Each loop iteration has fresh variables (since Go 1.22). Before that, closures and goroutines started inside a loop all saw the same variable, which was a notorious source of bugs; old articles still warn about it.
switchcases do not fall through. Each case ends by itself, a case may list several values (case "Sat", "Sun":), and the rare explicitfallthroughkeyword continues into the next case. Aswitchwith no expression is a tidy replacement for anif/else ifchain, as inclassify. Cases are tested top to bottom and need not be constants.- Labels.
break searchleaves the loop labelledsearch;continue labelworks too. Go also hasgoto, which you will almost never need.
Reading and writing control flow the Go way
Go code has a recognisable rhythm, and much of it comes from a habit experienced Go programmers call keeping the happy path on the left. Instead of nesting the main work inside conditions, a function checks for problems and returns early, so the normal case reads straight down the left margin:
func shippingCost(weightKg float64, country string) (float64, error) {
if weightKg <= 0 {
return 0, errors.New("weight must be positive")
}
rate, ok := ratePerKg[country]
if !ok {
return 0, fmt.Errorf("we don't ship to %q", country)
}
return weightKg * rate, nil
}Compare a version with if weightKg > 0 { if rate, ok := ...; ok { ... } else { ... } } else { ... }: the logic is the same, but the reader has to track two levels of nesting to find the answer. Go's linters even flag an else after a return as unnecessary.
A few other habits:
switch trueover longifchains. When three or more conditions are tested in order, an expressionlessswitchlines them up and makes the order visible.- Range loops over index loops.
for i, v := range itemsis clearer thanfor i := 0; i < len(items); i++and cannot run off the end. Use the three-part form when the step is unusual or you are not walking a collection. - No clever one-liners. Without a ternary operator, "pick a or b" is a four-line
if/elseor a small helper function. Go programmers accept the lines in exchange for code that reads the same in every file. (For the very common "smaller of two numbers", the built-inminandmaxfunctions arrived in Go 1.21.) - Named types for meaning.
type Celsius float64andtype Weekday intcost nothing at run time, and the compiler then refuses to mix aCelsiuswith a plainfloat64or aWeekdaywith a month number without an explicit conversion.
Worked example: leap years, three ways
The Gregorian calendar's rule is: a year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400. So 2024 and 2000 are leap years; 1900 and 2026 are not. Here is how the rule might be written three ways in Go, and why the last is what a reviewer would ask for.
A first draft nests conditions the way the sentence is spoken:
func isLeap(year int) bool {
if year%4 == 0 {
if year%100 == 0 {
return year%400 == 0
}
return true
}
return false
}It is correct, but the reader has to keep two open conditions in mind. A one-line boolean expression is shorter:
func isLeap(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}Many experienced Go programmers would accept this, but it takes a moment to check against the rule. An expressionless switch states each case in the order of the rule, most specific first:
func isLeap(year int) bool {
switch {
case year%400 == 0:
return true
case year%100 == 0:
return false
default:
return year%4 == 0
}
}Each line can be checked against the calendar rule on its own, the order of the cases carries the meaning ("400 overrides 100, which overrides 4"), and adding a case later is a one-line change. None of the three is slower than the others in any way that matters; the compiler turns all of them into a few comparisons. The choice is about the next person who has to read the code, which in Go is always the deciding argument.
Common misconceptions
Misconception
"Go checks integer overflow." It doesn't, in any build mode: integer arithmetic wraps around. Only constant expressions are checked, at compile time (var b byte = 300 is an error).
Misconception
":= is just a shorter =." := declares new variables; = assigns to existing ones. Inside an inner block, x := 5 creates a new x that hides the outer one, a frequent source of "why didn't my variable change?" bugs. go vet with the shadow analyser can catch some of these.
Misconception
"string(n) turns a number into text." It turns a code point into the character it stands for: string(rune(65)) is "A". Use strconv.Itoa(n) or fmt.Sprint(n) to get "65".
Misconception
"Go's switch falls through like C's." It doesn't. Each case is self-contained; break is unnecessary at the end of a case (inside a switch, break leaves the switch, not an enclosing loop, which is why labelled breaks exist). Use fallthrough explicitly in the rare case you want it.
Exercises
1. Types, variables and control flow
Warm-upComputationalWhat does fmt.Println(A, B, C) print, given this declaration?
const (
A = iota * 10
B
C
)
2. Types, variables and control flow
CoreComputationalWhat does this print? Write the lines separated by spaces.
switch n := 2; n {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
fallthrough
case 3:
fmt.Println("three")
case 4:
fmt.Println("four")
}
3. Types, variables and control flow
CoreComputationalWhat does this print?
var lvl uint8 = 200
lvl += 100
fmt.Println(lvl)
4. Types, variables and control flow
CoreComputationalWhat does this print? Write the two lines separated by a space.
x := 1
if x := 5; x > 3 {
x++
fmt.Println(x)
}
fmt.Println(x)
5. Types, variables and control flow
StretchComputationalWhat does this print?
a, b := 0.1, 0.2
fmt.Println(0.1+0.2 == 0.3, a+b == 0.3)
6. Types, variables and control flow
Warm-upComputationalWhat is total after this loop?
total := 0
for i := range 5 {
if i%2 == 0 {
continue
}
total += i
}