The ABCs of Go
I spent a couple days learning some Golang. This post, like so many others, consists of my personal notes.
Before I dived in, I had some questions, so I asked a few AIs:
- What are the major differences between Go and Python?
- No Classes/Inheritance: Go uses structs and interfaces. You don’t inherit code; you compositionally embed structs inside other structs.
- Pointers.
- Explicit Error Handling: Go does not use
try/exceptblocks. Functions regularly return an error object alongside data, and you must check it immediately.
- What’s the package manager or managers?
go mod: Go uses an integrated package management system called Go Modules (managed via the go CLI tool). You do not install a separate tool like pip. Instead, you use the standard Go toolchain to manage dependencies.- How to initialize a project: Run
go mod init <module-name> - How to install a package: Run
go get <package-url>
- Do you use virtual environments?
- No. Go does not use virtual environments like Python’s venv or virtualenv.
- Because Go projects use individual
go.modfiles to declare exactly which dependency versions they need, you can have multiple projects on your computer using completely different versions of the same library without any conflicts.
In Python,pip installdefaults to a global directory, requiring avenvto isolate projects.
In Go, download files are cached centrally in your home directory ($GOPATH/pkg/mod), but your project isolates its requirements locally via its module configuration.
- Do you use lock files?
- Yes. Go strictly utilizes lock files to ensure reproducible builds. Every Go module contains two files that act exactly like Python’s dependency tracking tools:
go.mod: equivalent torequirements.txtorpyproject.toml. Lists the direct dependencies and minimum versions your project requires. go.sum poetry.lock or Pipfile.lockgo.sum: equivalent topoetry.lockorPipfile.lock. This is the lock file. It lists the exact cryptographic hashes of every dependency (and transient dependency) to guarantee they never change unexpectedly.
- Yes. Go strictly utilizes lock files to ensure reproducible builds. Every Go module contains two files that act exactly like Python’s dependency tracking tools:
- What’s the workflow if I clone an existing repo? Do I have to do something like pip install but for go?
- When you clone an existing Go repository, you do not need to run an explicit installation command like pip install.
Go resolves and downloads missing dependencies automatically the very first time you try to run, build, or test the code. However, if you want to explicitly download everything right after cloning, you can run:go mod download
- When you clone an existing Go repository, you do not need to run an explicit installation command like pip install.
- Is Go Interpreted, Compiled, or Both?
- Go is a strictly compiled language. Unlike Python (which compiles to bytecode and runs on an interpreter) or Java (which runs on a Virtual Machine), Go compiles directly into native machine code (a single binary executable file) for your specific operating system and architecture.
- How to run the code?
- Approach A: run it directly (best for development).
You can use
go run .. This compiles your code behind the scenes into a temporary folder and executes it immediately. It feels like running an interpreted Python script. The dot.tells Go to look at the main package in the current directory - Approach B: Compile first, then execute.
You compile the project into a permanent, standalone binary executable using
go build -o myappand then run the binary directly via./myapp. Once built, thismyappbinary is entirely self-contained. It includes all your code and all dependencies. You can move this single file to another machine (with the same OS) and run it, without even installing Go on that machine.
- Approach A: run it directly (best for development).
You can use
- What is
go mod tidy?- It is a command for dependency management:
- Adds missing dependencies: If you imported a third-party library in your code but haven’t downloaded it yet, it finds, downloads, and adds it to
go.mod. - Removes unused dependencies: If you deleted a code block that used an external library, it cleans up
go.modby removing that library. - Updates
go.sum: It adds or removes cryptographic checksums so your builds remain secure and reproducible.
- Adds missing dependencies: If you imported a third-party library in your code but haven’t downloaded it yet, it finds, downloads, and adds it to
- It is a command for dependency management:
- How to test the code?
go testis the command used to automate the execution of test functions in your Go packages. Go has built-in support for testing. When you write a file ending in_test.go(e.g.,math_test.go) and include functions that start withTest(e.g.,func TestAdd(t *testing.T)), go test will find and execute them.- What it does: It compiles the source files and test files in the specified packages, runs the tests, and prints a summary (
PASSorFAIL). - Common variations:
go test ./...: Runs all tests in the current directory and all of its subdirectories.go test -v ./...: Runs all tests in “verbose” mode, showing exactly which tests are running and any logged output.go test -race ./...: Runs your tests with Go’s built-in data race detector enabled to find concurrency bugs.
Let’s go through the Tour of Go: https://go.dev/tour/list. Below is the public material and my notes.
1. Welcome
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
output:
Hello, 世界
Installation
wget https://go.dev/dl/go1.27.1.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.27.1.linux-amd64.tar.gz
vi ~/.profile
# Add: export PATH=$PATH:/usr/local/go/bin
# Add: export PATH="$PATH:$(go env GOPATH)/bin"
source ~/.profile
go version
The timestamp 2009-11-10 23:00:00 UTC is the official launch date and time (birthday) of the Go programming language, and it is used as the fixed starting time in the Go Playground Documentation.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Welcome to the playground!")
fmt.Println("The time is", time.Now())
}
output:
Welcome to the playground!
The time is 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2. Basics
Packages, variables, and functions
Packages
Every Go program is made up of packages.
Programs start running in package main.
This program is using the packages with import paths "fmt" and "math/rand".
By convention, the package name is the same as the last element of the import path. For instance, the "math/rand" package comprises files that begin with the statement package rand.
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("My favorite number is", rand.Intn(10))
}
output:
My favorite number is 6
Imports
This code groups the imports into a parenthesized, “factored” import statement.
You can also write multiple import statements, like:
import "fmt"
import "math"
But it is good style to use the factored import statement.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
}
output:
Now you have 2.6457513110645907 problems.
Exported names
In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package.
pizza and pi do not start with a capital letter, so they are not exported.
When importing a package, you can refer only to its exported names. Any “unexported” names are not accessible from outside the package.
Run the code. Notice the error message.
To fix the error, rename math.pi to math.Pi and try it again.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.pi)
}
output:
./prog.go:9:19: undefined: math.pi (but have Pi)
Go build failed.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Pi)
}
output:
3.141592653589793
Functions
A function can take zero or more arguments.
In this example, add takes two parameters of type int.
Notice that the type comes after the variable name.
(For more about why types look the way they do, see the article on Go’s declaration syntax.)
x int //x is an int
p *int //p is a pointer to int
a [3]int //array of 3 int
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
output:
55
Notice that the real main function in Go takes no arguments and has no type after it.
Functions continued
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
In this example, we shortened
x int, y int
to
x, y int
package main
import "fmt"
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
output:
55
Multiple results
A function can return any number of results.
The swap function returns two strings.
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
output:
world hello
Named return values
Go’s return values may be named. If so, they are treated as variables defined at the top of the function.
These names should be used to document the meaning of the return values.
A return statement without arguments returns the named return values. This is known as a “naked” return.
Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
output:
7 10
It rounded down 7.55, and rounded up 9.44
Variables
The var statement declares a list of variables; as in function argument lists, the type is last.
A var statement can be at package or function level. We see both in this example.
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
}
output:
0 false false false
integers take the default value of 0; booleans take the default value of false.
Variables with initializers
A var declaration can include initializers, one per variable.
If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
}
output:
1 2 true false no!
Short variable declarations
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
}
output:
1 2 3 true false no!
Basic types
Go’s basic types are
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
The example shows variables of several types, and also that variable declarations may be “factored” into blocks, as with import statements.
The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
fmt.Printf("Type: %T Value: %v\n", z, z)
}
output:
Type: bool Value: false
Type: uint64 Value: 18446744073709551615
Type: complex128 Value: (2+3i)
%T is type.
%v is value.
\n is just a standard newline break.
1<<64 - 1 $ = 2^{64}-1$
Remember that in $\mathbb{C}$, $i^2 = -1$
Zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
0 for numeric types,
false for the boolean type, and
"" (the empty string) for strings.
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
}
output:
0 0 false ""
%q is a quoted string.
Type conversions
The expression T(v) converts the value v to the type T.
Some numeric conversions:
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
Or, put more simply:
i := 42
f := float64(i)
u := uint(f)
Unlike in C, in Go assignment between items of different type requires an explicit conversion. Try removing the float64 or uint conversions in the example and see what happens.
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z uint = uint(f)
fmt.Println(x, y, z)
}
output:
3 4 5
If you remove the explicit conversion, you get this kind of error: ./prog.go:11:15: cannot use f (variable of type float64) as uint value in variable declaration
Type inference
When declaring a variable without specifying an explicit type (either by using the := syntax or var = expression syntax), the variable’s type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
var i int
j := i // j is an int
But when the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:
i := 42 // int
f := 3.142 // float64
g := 0.867 + 0.5i // complex128
Try changing the initial value of v in the example code and observe how its type is affected.
package main
import "fmt"
func main() {
v := 42 // change me!
fmt.Printf("v is of type %T\n", v)
}
output:
v is of type int
Constants
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.
package main
import "fmt"
const Pi = 3.14
func main() {
const World = "世界"
fmt.Println("Hello", World)
fmt.Println("Happy", Pi, "Day")
const Truth = true
fmt.Println("Go rules?", Truth)
}
output:
Hello 世界
Happy 3.14 Day
Go rules? true
Numeric constants
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.
Try printing needInt(Big) too.
(An int can store at maximum a 64-bit integer, and sometimes less.)
package main
import "fmt"
const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
}
output:
21
0.2
1.2676506002282295e+29
If we try fmt.Println(needInt(Big)), we get the error ./prog.go:22:22: cannot use Big (untyped int constant 1267650600228229401496703205376) as int value in argument to needInt (overflows).
Big overflows int: A standard 64-bit integer (int or int64) can only hold values up to $2^{63}-1$. Because Big represents $2^{100}$, trying to pass it into needInt(Big) will trigger a compile-time overflow error.
Big fits in float64: A float64 can represent values up to roughly $1.8 \times 10^{308}$, so it can easily accommodate $2^{100}$ (which is about $1.27 \times 10^{30}$).
Flow control statements: for, if, else, switch, and defer
For
Go has only one looping construct, the for loop.
The basic for loop has three components separated by semicolons:
the init statement: executed before the first iteration
the condition expression: evaluated before every iteration
the post statement: executed at the end of every iteration
The init statement will often be a variable declaration, and the variables declared there are visible only in the scope of the for statement.
The loop will stop iterating once the boolean condition evaluates to false.
Note: Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
output:
45
For continued
The init and post statements are optional.
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
}
output:
1024
For is Go’s “while”
At that point you can drop the semicolons: C’s while is spelled for in Go.
package main
import "fmt"
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}
output:
1024
Forever
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
package main
func main() {
for {
}
}
If
Go’s if statements are like its for loops; the expression need not be surrounded by parentheses ( ) but the braces { } are required.
package main
import (
"fmt"
"math"
)
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
output:
1.4142135623730951 2i
If with a short statement
Like for, the if statement can start with a short statement to execute before the condition.
Variables declared by the statement are only in scope until the end of the if.
(Try using v in the last return statement.)
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
output:
9 20
If you try using v in the last return statement you get the error ./prog.go:12:14: undefined: v.
If and else
Variables declared inside an if short statement are also available inside any of the else blocks.
(Both calls to pow return their results before the call to fmt.Println in main begins.)
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
output:
27 >= 20
9 20
%g is a formatting verb to print floating-point numbers in a compact representation.
First call: pow(3, 2, 10). It returns 9. Nothing is printed to the console yet.
Second Call: pow(3, 3, 20). The else block is executed and prints 27 >= 20, and then returns 20.
The final print: the fmt.Println statement in main() receives the two returned values and prints them side by side 9 20.
Exercise: Loops and Functions
As a way to play with functions and loops, let’s implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.
Computers typically compute the square root of x using a loop. Starting with some guess z, we can adjust z based on how close z² is to x, producing a better guess:
z -= (z*z - x) / (2*z)
Repeating this adjustment makes the guess better and better until we reach an answer that is as close to the actual square root as can be.
Implement this in the func Sqrt provided. A decent starting guess for z is 1, no matter what the input. To begin with, repeat the calculation 10 times and print each z along the way. See how close you get to the answer for various values of x (1, 2, 3, …) and how quickly the guess improves.
Hint: To declare and initialize a floating point value, give it floating point syntax or use a conversion:
z := 1.0
z := float64(1)
Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). See if that’s more or fewer than 10 iterations. Try other initial guesses for z, like x, or x/2. How close are your function’s results to the math.Sqrt in the standard library?
(Note: If you are interested in the details of the algorithm, the z² − x above is how far away z² is from where it needs to be (x), and the division by 2z is the derivative of z², to scale how much we adjust z by how quickly z² is changing. This general approach is called Newton’s method. It works well for many functions but especially well for square root.)
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 1; i <= 10; i++ {
z -= (z*z - x) / (2 * z)
}
return z
}
func main() {
fmt.Println(Sqrt(17))
fmt.Printf("Standard math.Sqrt: %v\n", math.Sqrt(17))
}
output:
4.123105625617661
Standard math.Sqrt: 4.123105625617661
Switch
A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.
Go’s switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case in those languages is provided automatically in Go. Another important difference is that Go’s switch cases need not be constants, and the values involved need not be integers.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("macOS.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
}
}
output:
Go runs on Linux.
Switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
(For example,
switch i {
case 0:
case f():
}
does not call f if i==0.)
Note: Time in the Go playground always appears to start at 2009-11-10 23:00:00 UTC, a value whose significance is left as an exercise for the reader.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("When's Saturday?")
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("Today.")
case today + 1:
fmt.Println("Tomorrow.")
case today + 2:
fmt.Println("In two days.")
default:
fmt.Println("Too far away.")
}
}
output:
When's Saturday?
Too far away.
time.Saturday is a constant of the type time.Weekday which an integer. The days of the week are numbered sequentially starting from Sunday: time.Sunday = 0, time.Monday = 1 … time.Saturday = 6.
2009-11-10 was a Tuesday, and therefore today = 2. So the case that got applied is the default one.
Switch with no condition
Switch without a condition is the same as switch true.
This construct can be a clean way to write long if-then-else chains.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
output:
Good evening.
It is 2009-11-10 23:00:00 UTC.
Interesting. So when we have something immediately after switch it gets compared to the cases via a == and if none matches it goes to the default.
But if we have nothing immediately after switch then the conditions are in the cases.
Defer
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
output:
hello
world
Stacking defers
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
To learn more about defer statements read this blog post.
package main
import "fmt"
func main() {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
fmt.Println("done")
}
output:
counting
done
9
8
7
6
5
4
3
2
1
0
More types: structs, slices, and maps
Pointers
Go has pointers. A pointer holds the memory address of a value.
The type *T is a pointer to a T value. Its zero value is nil.
var p *int
The & operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer’s underlying value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is known as “dereferencing” or “indirecting”.
Unlike C, Go has no pointer arithmetic.
package main
import "fmt"
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
output:
42
21
73
&(Address-of operator): Turns a value into a pointer. It means “Get the memory address of this variable.”*(Dereference / Type operator): Has two meanings depending on where you use it:- In a type definition (
*int): It means “This variable is a pointer that holds an address.” - In front of a variable (
*myPointer): It means “Go to the address this pointer is holding and give me the actual value.”
- In a type definition (
Structs
A struct is a collection of fields.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{1, 2})
}
output:
{1 2}
Struct Fields
Struct fields are accessed using a dot.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
output:
4
Pointers to Structs
Struct fields can be accessed through a struct pointer.
To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
}
output:
{1000000000 2}
So we could have written it in 2 other different ways and we would have gotten the same result:
func main() {
v := Vertex{1, 2}
p := &v
(*p).X = 1e9
fmt.Println(v)
}
OR
func main() {
v := Vertex{1, 2}
//p := &v // we comment it out because p would be a declared but unused variable.
v.X = 1e9
fmt.Println(v)
}
p is a pointer to v: p := &v, meaning that p contains the memory address of where v is.
*p: * means go to memory address of pointer p and get the value of what’s there, which is v.
I understand the concept. The syntax needs some muscle memory to get used to.
Struct Literals
A struct literal denotes a newly allocated struct value by listing the values of its fields.
You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)
The special prefix & returns a pointer to the struct value.
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
}
output:
{1 2} &{1 2} {1 0} {0 0}
Arrays
The type [n]T is an array of n values of type T.
The expression
var a [10]int
declares a variable a as an array of ten integers.
An array’s length is part of its type, so arrays cannot be resized. This seems limiting, but don’t worry; Go provides a convenient way of working with arrays.
package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
}
output:
Hello World
[Hello World]
[2 3 5 7 11 13]
Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.
The type []T is a slice with elements of type T.
A slice is formed by specifying two indices, a low and high bound, separated by a colon:
a[low : high]
This selects a half-open range which includes the first element, but excludes the last one.
The following expression creates a slice which includes elements 1 through 3 of a:
a[1:4]
package main
import "fmt"
func main() {
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s)
}
output:
[3 5 7]
Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.
Changing the elements of a slice modifies the corresponding elements of its underlying array.
Other slices that share the same underlying array will see those changes.
package main
import "fmt"
func main() {
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
}
output:
[John Paul George Ringo]
[John Paul] [Paul George]
[John XXX] [XXX George]
[John XXX George Ringo]
Slice literals
A slice literal is like an array literal without the length.
This is an array literal:
[3]bool{true, true, false}
And this creates the same array as above, then builds a slice that references it:
[]bool{true, true, false}
package main
import "fmt"
func main() {
q := []int{2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{true, false, true, true, false, true}
fmt.Println(r)
s := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
fmt.Println(s)
}
output:
[2 3 5 7 11 13]
[true false true true false true]
[{2 true} {3 false} {5 true} {7 true} {11 false} {13 true}]
Slice defaults
When slicing, you may omit the high or low bounds to use their defaults instead.
The default is zero for the low bound and the length of the underlying slice or array for the high bound.
For the array
var a [10]int
these slice expressions are equivalent:
a[0:10]
a[:10]
a[0:]
a[:]
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
s = s[1:4]
fmt.Println(s)
s = s[:2]
fmt.Println(s)
s = s[1:]
fmt.Println(s)
}
output:
[3 5 7]
[3 5]
[5]
Slice length and capacity
A slice has both a length and a capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).
You can extend a slice’s length by re-slicing it, provided it has sufficient capacity. Try changing one of the slice operations in the example program to extend it beyond its capacity and see what happens.
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
output:
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
%d is a format specifier (or format verb) used to represent a base-10 (decimal) integer.
If you try to extend the slice beyond its capacity you get this type of error:
panic: runtime error: slice bounds out of range [:7] with capacity 6
goroutine 1 [running]:
main.main()
/tmp/sandbox1653071883/prog.go:18 +0x92
Nil slices
The zero value of a slice is nil.
A nil slice has a length and capacity of 0 and has no underlying array.
package main
import "fmt"
func main() {
var s []int
fmt.Println(s, len(s), cap(s))
if s == nil {
fmt.Println("nil!")
}
}
output:
[] 0 0
nil!
Creating a slice with make
Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.
The make function allocates a zeroed array and returns a slice that refers to that array:
a := make([]int, 5) // len(a)=5
To specify a capacity, pass a third argument to make:
b := make([]int, 0, 5) // len(b)=0, cap(b)=5
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:] // len(b)=4, cap(b)=4
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
output:
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]
%s is a format specifier (or format verb) used to represent a string or a slice of uninterpreted bytes.
Slices of slices
Slices can contain any type, including other slices.
package main
import (
"fmt"
"strings"
)
func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
// The players take turns.
board[0][0] = "X"
board[2][2] = "O"
board[1][2] = "X"
board[1][0] = "O"
board[0][2] = "X"
for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
output:
X _ X
O _ X
_ _ O
Notice the new module strings and is function strings.Join().
Appending to a slice
It is common to append new elements to a slice, and so Go provides a built-in append function. The documentation of the built-in package describes append.
func append(s []T, vs ...T) []T
The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.
The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
(To learn more about slices, read the Slices: usage and internals article.)
package main
import "fmt"
func main() {
var s []int
printSlice(s)
// append works on nil slices.
s = append(s, 0)
printSlice(s)
// The slice grows as needed.
s = append(s, 1)
printSlice(s)
// We can add more than one element at a time.
s = append(s, 2, 3, 4)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
output:
len=0 cap=0 []
len=1 cap=1 [0]
len=2 cap=2 [0 1]
len=5 cap=6 [0 1 2 3 4]
Why in the end the len is 5 but the cap is 6?
Because of how Go allocates memory under the hood to make appending efficient.
Go’s growth algorithm calculates a new capacity (usually doubling the requested size or rounding up to the next memory block allocator size). In this case, the Go runtime allocates a block of memory that fits 6 elements to avoid frequent allocations in the near future.
To keep append fast, Go allocates more memory than it immediately needs. This ensures that if you append another element next (making len 6), Go won’t have to allocate new memory again, it will just reuse the extra space it already set aside.
Range
The range form of the for loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
package main
import "fmt"
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
output:
2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128
Range continued
You can skip the index or value by assigning to _.
for i, _ := range pow
for _, value := range pow
If you only want the index, you can omit the second variable.
for i := range pow
package main
import "fmt"
func main() {
pow := make([]int, 10)
fmt.Println(pow)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
fmt.Println(pow)
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
output:
[0 0 0 0 0 0 0 0 0 0]
[1 2 4 8 16 32 64 128 256 512]
1
2
4
8
16
32
64
128
256
512
Exercise: Slices
Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y.
(You need to use a loop to allocate each []uint8 inside the [][]uint8.)
(Use uint8(intValue) to convert between types.)
package main
import "golang.org/x/tour/pic"
// Pic allocates and returns a slice of length dy,
// where each element is a slice of dx 8-bit unsigned integers.
func Pic(dx, dy int) [][]uint8 {
// Allocate the outer slice of length dy
picture := make([][]uint8, dy)
for y := 0; y < dy; y++ {
// Allocate each inner slice of length dx
picture[y] = make([]uint8, dx)
for x := 0; x < dx; x++ {
// Choose an interesting function to generate the pixel value.
// Examples: (x+y)/2, x*y, x^y
picture[y][x] = uint8(x ^ y)
}
}
return picture
}
func main() {
pic.Show(Pic)
}
Maps
A map maps keys to values.
The zero value of a map is nil. A nil map has no keys, nor can keys be added.
The make function returns a map of the given type, initialized and ready for use.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func main() {
fmt.Println(m)
m = make(map[string]Vertex)
fmt.Println(m, len(m))
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m, len(m))
fmt.Println(m["Bell Labs"])
}
output:
map[]
map[] 0
map[Bell Labs:{40.68433 -74.39967}] 1
{40.68433 -74.39967}
Map literals
Map literals are like struct literals, but the keys are required.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
func main() {
fmt.Println(m)
fmt.Println(len(m))
fmt.Println(m["Google"])
}
output:
map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]
2
{37.42202 -122.08408}
Map literals continued
If the top-level type is just a type name, you can omit it from the elements of the literal.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
func main() {
fmt.Println(m)
}
output:
map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]
Mutating maps
Insert or update an element in map m:
m[key] = elem
Retrieve an element:
elem = m[key]
Delete an element:
delete(m, key)
Test that a key is present with a two-value assignment:
elem, ok = m[key]
If key is in m, ok is true. If not, ok is false.
If key is not in the map, then elem is the zero value for the map’s element type.
Note: If elem or ok have not yet been declared you could use a short declaration form:
elem, ok := m[key]
package main
import "fmt"
func main() {
m := make(map[string]int)
m["Answer"] = 42
fmt.Println(m)
fmt.Println("The value:", m["Answer"])
m["Answer"] = 48
fmt.Println(m)
fmt.Println("The value:", m["Answer"])
delete(m, "Answer")
fmt.Println(m)
fmt.Println("The value:", m["Answer"])
v, ok := m["Answer"]
fmt.Println(m)
fmt.Println("The value:", v, "Present?", ok)
}
output:
map[Answer:42]
The value: 42
map[Answer:48]
The value: 48
map[]
The value: 0
map[]
The value: 0 Present? false
Exercise: Maps
Implement WordCount. It should return a map of the counts of each “word” in the string s. The wc.Test function runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.
package main
import (
"strings"
"golang.org/x/tour/wc"
)
// WordCount returns a map of the counts of each “word” in the string s.
func WordCount(s string) map[string]int {
// Create an empty map to store word counts
counts := make(map[string]int)
// Split the string into a slice of words based on whitespace
words := strings.Fields(s)
// Iterate through the slice and increment the count for each word
for _, word := range words {
counts[word]++
}
return counts
}
func main() {
wc.Test(WordCount)
}
output:
PASS
f("I am learning Go!") =
map[string]int{"Go!":1, "I":1, "am":1, "learning":1}
PASS
f("The quick brown fox jumped over the lazy dog.") =
map[string]int{"The":1, "brown":1, "dog.":1, "fox":1, "jumped":1, "lazy":1, "over":1, "quick":1, "the":1}
PASS
f("I ate a donut. Then I ate another donut.") =
map[string]int{"I":2, "Then":1, "a":1, "another":1, "ate":2, "donut.":2}
PASS
f("A man a plan a canal panama.") =
map[string]int{"A":1, "a":2, "canal":1, "man":1, "panama.":1, "plan":1}
Function values
Functions are values too. They can be passed around just like other values.
Function values may be used as function arguments and return values.
package main
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow))
}
output:
13
5
81
Function closures
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.
For example, the adder function returns a closure. Each closure is bound to its own sum variable.
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
output:
0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90
Exercise: Fibonacci closure
Let’s have some fun with functions.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, …).
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
// Initialize the first two numbers before the sequence starts.
// a tracks the current number to return, and b tracks the next number.
a, b := 0, 1
return func() int {
// Store the current value of a to return later
current := a
// Calculate the next numbers in the sequence
a, b = b, a + b
// Return the current Fibonacci number
return current
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
output:
0
1
1
2
3
5
8
13
21
34
3. Methods and Interfaces
Methods and interfaces
Methods
Go does not have classes. However, you can define methods on types.
A method is a function with a special receiver argument.
The receiver appears in its own argument list between the func keyword and the method name.
In this example, the Abs method has a receiver of type Vertex named v.
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(v.Abs())
}
output:
5
Methods are functions
Remember: a method is just a function with a receiver argument.
Here’s Abs written as a regular function with no change in functionality.
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func Abs(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(Abs(v))
}
output:
5
Methods continued
You can declare a method on non-struct types, too.
In this example we see a numeric type MyFloat with an Abs method.
You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).
package main
import (
"fmt"
"math"
)
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func main() {
f := MyFloat(-math.Sqrt2)
fmt.Println(f.Abs())
}
output:
1.4142135623730951
math.Sqrt2 is a built-in Go constant representing the square root of 2 ($\approx 1.41421$).
Pointer receivers
You can declare methods with pointer receivers.
This means the receiver type has the literal syntax *T for some type T. (Also, T cannot itself be a pointer such as *int.)
For example, the Scale method here is defined on *Vertex.
Methods with pointer receivers can modify the value to which the receiver points (as Scale does here). Since methods often need to modify their receiver, pointer receivers are more common than value receivers.
Try removing the * from the declaration of the Scale function on line 16 and observe how the program’s behavior changes.
With a value receiver, the Scale method operates on a copy of the original Vertex value. (This is the same behavior as for any other function argument.) The Scale method must have a pointer receiver to change the Vertex value declared in the main function.
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
v.Scale(10)
fmt.Println(v.Abs())
}
output:
50
If we remove the * from the Scale method receiver (changing func (v *Vertex) Scale(f float64) to func (v Vertex) Scale(f float64)), the code will print 5 instead of 50.
Without the pointer (*), Scale receives a copy of the Vertex struct rather than a reference to the original variable v.
Inside the modified Scale method, the multiplication only modifies that local copy. The original v in the main function remains completely untouched ({3, 4}).
Pointers and functions
Here we see the Abs and Scale methods rewritten as functions.
Again, try removing the * from line 16. Can you see why the behavior changes? What else did you need to change for the example to compile?
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func Abs(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func Scale(v *Vertex, f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
Scale(&v, 10)
fmt.Println(Abs(v))
}
output:
50
If we remove the * from line 16, the program will fail to compile because of a type mismatch on line 22.
By changing func Scale(v *Vertex, f float64) to func Scale(v Vertex, f float64), the function now accepts a value instead of a pointer. Just like with the method example, it will now operate on a local copy of Vertex, leaving the original v in main unscaled.
Go is strictly typed, so passing a pointer (&v) into a function expecting a value (Vertex) causes a compiler error. To make the code compile, we must make two additional changes on line 22:
- Remove the ampersand (
&) fromScale(&v, 10)so we are passing the value directly:Scale(v, 10). - Reassign the result (which requires updating the
Scalefunction to return the modified struct) if we still want the value to actually update inmain. Without adding areturnstatement, the code will compile withScale(v, 10), but it will print5because the originalvremains unmodified.
Here’s how we would write it to continue giving us the50:
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func Abs(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
// Notice the return, but also the Vertex type (for the function itself)!!!!
func Scale(v Vertex, f float64) Vertex {
v.X = v.X * f
v.Y = v.Y * f
return v
}
func main() {
v := Vertex{3, 4}
// Passed by value and reassigned to update v
v = Scale(v, 10)
fmt.Println(Abs(v))
}
Methods and pointer indirection
Comparing the previous two programs, you might notice that functions with a pointer argument must take a pointer:
var v Vertex
ScaleFunc(v, 5) // Compile error!
ScaleFunc(&v, 5) // OK
while methods with pointer receivers take either a value or a pointer as the receiver when they are called:
var v Vertex
v.Scale(5) // OK
p := &v
p.Scale(10) // OK
For the statement v.Scale(5), even though v is a value and not a pointer, the method with the pointer receiver is called automatically. That is, as a convenience, Go interprets the statement v.Scale(5) as (&v).Scale(5) since the Scale method has a pointer receiver.
package main
import "fmt"
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func ScaleFunc(v *Vertex, f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
v.Scale(2)
ScaleFunc(&v, 10)
p := &Vertex{4, 3}
p.Scale(3)
ScaleFunc(p, 8)
fmt.Println(v, p)
}
output:
{60 80} &{96 72}
Go methods with pointer receivers automatically handle pointer indirection, whereas regular functions require exact type matching:
- Methods vs. Functions with Values (
v)v.Scale(2)(Method): Even thoughvis a value (Vertex) andScaleexpects a pointer (*Vertex), Go automatically interprets this as(&v).Scale(2).ScaleFunc(&v, 10)(Function): Regular functions do not have this convenience. You must explicitly pass the address using&vto match the*Vertexparameter.
- Methods vs. Functions with Pointers (
p)p.Scale(3)(Method): Sincepis already a pointer (*Vertex), it matches the method receiver perfectly.ScaleFunc(p, 8)(Function): The pointerpis passed directly to the function because the types match exactly.
Both v and p are permanently modified in place by all calls because they all ultimately operate via pointers, printing: {60 80} &{96 72}.
If we wanted in the end to get values for both ({60 80} {96 72}), we would use fmt.Println(v, *p) instead of fmt.Println(v, p).
Methods and pointer indirection (2)
The equivalent thing happens in the reverse direction.
Functions that take a value argument must take a value of that specific type:
var v Vertex
fmt.Println(AbsFunc(v)) // OK
fmt.Println(AbsFunc(&v)) // Compile error!
while methods with value receivers take either a value or a pointer as the receiver when they are called:
var v Vertex
fmt.Println(v.Abs()) // OK
p := &v
fmt.Println(p.Abs()) // OK
In this case, the method call p.Abs() is interpreted as (*p).Abs().
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func AbsFunc(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(v.Abs())
fmt.Println(AbsFunc(v))
p := &Vertex{4, 3}
fmt.Println(p.Abs())
fmt.Println(AbsFunc(*p))
}
output:
5
5
5
5
So basically methods are more “lax” regarding pointer syntax (you do not have to write the & symbol) because Go limits this automatic syntactic sugar (pointer indirection) to methods while keeping regular functions strict.
Choosing a value or pointer receiver
There are two reasons to use a pointer receiver.
The first is so that the method can modify the value that its receiver points to.
The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.
In this example, both Scale and Abs are methods with receiver type *Vertex, even though the Abs method needn’t modify its receiver.
In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both. (We’ll see why over the next few pages.)
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := &Vertex{3, 4}
fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
v.Scale(5)
fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}
output:
Before scaling: &{X:3 Y:4}, Abs: 5
After scaling: &{X:15 Y:20}, Abs: 25
Interfaces
An interface type is defined as a set of method signatures.
A value of interface type can hold any value that implements those methods.
Note: There is an error in the example code on line 22. Vertex (the value type) doesn’t implement Abser because the Abs method is defined only on *Vertex (the pointer type).
package main
import (
"fmt"
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat implements Abser
a = &v // a *Vertex implements Abser
// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v
fmt.Println(a.Abs())
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
output:
./prog.go:22:6: cannot use v (variable of struct type Vertex) as Abser value in assignment: Vertex does not implement Abser (method Abs has pointer receiver)
We have 2 choices to fix it:
- Pass by reference: Change line 22 to
a = &v. This satisfies the interface because*Vertexexplicitly implementsAbs(). - Change the receiver: If
Abs()doesn’t actually need to modify the coordinates (which it doesn’t), change the method definition to a value receiver:func (v Vertex) Abs() float64(line 40). Once we remove the*(line 40), bothVertexand*Vertexwill automatically satisfy the interface.
Interfaces are implemented implicitly
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.
Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.
package main
import "fmt"
type I interface {
M()
}
type T struct {
S string
}
// This method means type T implements the interface I,
// but we don't need to explicitly declare that it does so.
func (t T) M() {
fmt.Println(t.S)
}
func main() {
var i I = T{"hello"}
i.M()
}
output:
hello
Interface values
Under the hood, interface values can be thought of as a tuple of a value and a concrete type:
(value, type)
An interface value holds a value of a specific underlying concrete type.
Calling a method on an interface value executes the method of the same name on its underlying type.
package main
import (
"fmt"
"math"
)
type I interface {
M()
}
type T struct {
S string
}
func (t *T) M() {
fmt.Println(t.S)
}
type F float64
func (f F) M() {
fmt.Println(f)
}
func main() {
var i I
i = &T{"Hello"}
describe(i)
i.M()
i = F(math.Pi)
describe(i)
i.M()
}
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
output:
(&{Hello}, *main.T)
Hello
(3.141592653589793, main.F)
3.141592653589793
An interface acts like a contract. Because the interface I declares M(), any type in the entire program can implement its own version of M().
- When
iholds the struct&T{"Hello"},i.M()triggers the struct’s version ofM(). - When
iholds the floatF(math.Pi),i.M()triggers the float’s version ofM().
Interface values with nil underlying values
If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.
In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)
Note that an interface value that holds a nil concrete value is itself non-nil.
package main
import "fmt"
type I interface {
M()
}
type T struct {
S string
}
func (t *T) M() {
if t == nil {
fmt.Println("<nil>")
return
}
fmt.Println(t.S)
}
func main() {
var i I
var t *T
i = t
describe(i)
i.M()
i = &T{"hello"}
describe(i)
i.M()
}
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
output:
(<nil>, *main.T)
<nil>
(&{hello}, *main.T)
hello
Nil interface values
A nil interface value holds neither value nor concrete type.
Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.
package main
import "fmt"
type I interface {
M()
}
func main() {
var i I
describe(i)
i.M()
}
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
output:
(<nil>, <nil>)
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49ad59]
goroutine 1 [running]:
main.main()
/tmp/sandbox1114554762/src/prog.go:12 +0x19
The empty interface
The interface type that specifies zero methods is known as the empty interface:
interface{}
An empty interface may hold values of any type. (Every type implements at least zero methods.)
any is an alias for interface{}, and the two are completely equivalent.
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type any.
package main
import "fmt"
func main() {
var i interface{}
describe(i)
i = 42
describe(i)
i = "hello"
describe(i)
}
func describe(i interface{}) {
fmt.Printf("(%v, %T)\n", i, i)
}
output:
(<nil>, <nil>)
(42, int)
(hello, string)
Type assertions
A type assertion provides access to an interface value’s underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
Note the similarity between this syntax and that of reading from a map.
package main
import "fmt"
func main() {
var i interface{} = "hello"
s := i.(string)
fmt.Println(s)
s, ok := i.(string)
fmt.Println(s, ok)
f, ok := i.(float64)
fmt.Println(f, ok)
f = i.(float64) // panic
fmt.Println(f)
}
output:
hello
hello true
0 false
panic: interface conversion: interface {} is string, not float64
goroutine 1 [running]:
main.main()
/tmp/sandbox972808973/src/prog.go:17 +0x13f
Type switches
A type switch is a construct that permits several type assertions in series.
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
switch v := i.(type) {
case T:
// here v has type T
case S:
// here v has type S
default:
// no match; here v has the same type as i
}
The declaration in a type switch has the same syntax as a type assertion i.(T), but the specific type T is replaced with the keyword type.
This switch statement tests whether the interface value i holds a value of type T or S. In each of the T and S cases, the variable v will be of type T or S respectively and hold the value held by i. In the default case (where there is no match), the variable v is of the same interface type and value as i.
package main
import "fmt"
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
func main() {
do(21)
do("hello")
do(true)
}
output:
Twice 21 is 42
"hello" is 5 bytes long
I don't know about type bool!
Stringers
One of the most ubiquitous interfaces is Stringer defined by the fmt package.
type Stringer interface {
String() string
}
A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func main() {
a := Person{"Arthur Dent", 42}
z := Person{"Zaphod Beeblebrox", 9001}
fmt.Println(a, z)
}
output:
Arthur Dent (42 years) Zaphod Beeblebrox (9001 years)
What kind of weirdness is this?!?! The String() method always gets applied automatically without being invoked explicitly?
Yes, it gets applied automatically, but only because we are passing it to the fmt package functions (like Println, Printf, or Sprint).
Whenever we pass a variable to fmt.Println, the function checks behind the scenes if that variable’s type implements the Stringer interface.
- If it does:
fmt.Printlnautomatically calls your customString().method to get the string representation. - If it doesn’t:
fmt.Printlnfalls back to its default formatting (which for a struct looks like{Arthur Dent 42}).
Exercise: Stringers
Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.
For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4".
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ia IPAddr) String() string {
return fmt.Sprintf("%v.%v.%v.%v", ia[0], ia[1], ia[2], ia[3])
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, ip)
}
}
output:
loopback: 127.0.0.1
googleDNS: 8.8.8.8
Errors
Go programs express error state with error values.
The error type is a built-in interface similar to fmt.Stringer:
type error interface {
Error() string
}
(As with fmt.Stringer, the fmt package looks for the error interface when printing values.)
Functions often return an error value, and calling code should handle errors by testing whether the error equals nil.
i, err := strconv.Atoi("42")
if err != nil {
fmt.Printf("couldn't convert number: %v\n", err)
return
}
fmt.Println("Converted integer:", i)
A nil error denotes success; a non-nil error denotes failure.
There are a couple things to understand there:
strconv: This is a built-in Go package used for converting string representations to and from basic data types.Atoi: This stands for ASCII to i (integer). It is a function specifically designed to parse a decimal string and change it into a standard Gointtype.
package main
import (
"fmt"
"time"
)
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("at %v, %s",
e.When, e.What)
}
func run() error {
return &MyError{
time.Now(),
"it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
output:
at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, it didn't work
Exercise: Errors
Copy your Sqrt function from the earlier exercise and modify it to return an error value.
Sqrt should return a non-nil error value when given a negative number, as it doesn’t support complex numbers.
Create a new type
type ErrNegativeSqrt float64
and make it an error by giving it a
func (e ErrNegativeSqrt) Error() string
method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2".
Note: A call to fmt.Sprint(e) inside the Error method will send the program into an infinite loop. You can avoid this by converting e first: fmt.Sprint(float64(e)). Why?
Change your Sqrt function to return an ErrNegativeSqrt value when given a negative number.
package main
import (
"fmt"
)
// 1. Create the custom error type
type ErrNegativeSqrt float64
// 2. Implement the error interface
func (e ErrNegativeSqrt) Error() string {
// Cast e to float64 to break the infinite print loop
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
// 3. Update Sqrt to return both a float64 and an error
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := 1.0
for i := 1; i <= 10; i++ {
z -= (z*z - x) / (2 * z)
}
return 0, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
output:
0 <nil>
0 cannot Sqrt negative number: -2
Explanation of the infinite loop:
- The Trigger: The
fmtpackage automatically checks if any variable passed to it implements theerrorinterface. If it does, it implicitly calls its.Error()method to print it. - The Loop: Calling
fmt.Sprint(e)inside theError()method tells Go to formate. To formate, Go callsError(), which callsfmt.Sprint(e), which callsError()again, creating an infinite recursive loop. - The Fix: Converting
eto a raw primitive (float64(e)) strips away the custom type. A standardfloat64does not have anError()method, so Go safely prints the number without re-triggering the loop.
Readers
The io package specifies the io.Reader interface, which represents the read end of a stream of data.
The Go standard library contains many implementations of this interface, including files, network connections, compressors, ciphers, and others.
The io.Reader interface has a Read method:
func (T) Read(b []byte) (n int, err error)
Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.
The example code creates a strings.Reader and consumes its output 8 bytes at a time.
package main
import (
"fmt"
"io"
"strings"
)
func main() {
r := strings.NewReader("Hello, Reader!")
b := make([]byte, 8)
for {
n, err := r.Read(b)
fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
fmt.Printf("b[:n] = %q\n", b[:n])
if err == io.EOF {
break
}
}
}
output:
n = 8 err = <nil> b = [72 101 108 108 111 44 32 82]
b[:n] = "Hello, R"
n = 6 err = <nil> b = [101 97 100 101 114 33 32 82]
b[:n] = "eader!"
n = 0 err = EOF b = [101 97 100 101 114 33 32 82]
b[:n] = ""
Let’s break this down:
r := strings.NewReader(...): Creates a stream containing the string"Hello, Reader!"(14 total bytes).b := make([]byte, 8): Creates a temporary 8-byte buffer (scratchpad) to hold data during each read cycle.n, err := r.Read(b): Fills the bufferbwith up to 8 bytes. It returnsn(the number of bytes successfully read) and anerr(if any occurred).b[:n]: Slices the buffer to print only the new bytes read during this iteration, ignoring any leftover data from previous loops.if err == io.EOF: Checks if the stream has reached the End Of File. Once true, the loop breaks. Therefore:- Iteration 1: Reads the first 8 bytes (
"Hello, R").n = 8,err = <nil>. - Iteration 2: Reads the remaining 6 bytes (
"eader!").n = 6,err = <nil>. The buffer now looks like[e a d e r ! , R]because the last two bytes from the first read (, R) were not overwritten. Slicingb[:6]safely extracts only"eader!". - Iteration 3: The stream is empty.
n = 0,err = EOF. The loop breaks.
Exercise: Readers
Implement a Reader type that emits an infinite stream of the ASCII character 'A'.
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (r MyReader) Read(b []byte) (int, error) {
// Loop through the entire capacity of the slice passed by the caller
for i := range b {
b[i] = 'A'
}
// Return the number of bytes written and a nil error (since it never ends)
return len(b), nil
}
func main() {
reader.Validate(MyReader{})
}
output:
OK!
Exercise: rot13Reader
A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way.
For example, the gzip.NewReader function takes an io.Reader (a stream of compressed data) and returns a *gzip.Reader that also implements io.Reader (a stream of the decompressed data).
Implement a rot13Reader that implements io.Reader and reads from an io.Reader, modifying the stream by applying the rot13 substitution cipher to all alphabetical characters.
The rot13Reader type is provided for you. Make it an io.Reader by implementing its Read method.
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
// Read reads from the underlying reader and decodes the stream using ROT13
func (r *rot13Reader) Read(b []byte) (int, error) {
// 1. Read from the underlying io.Reader into the buffer
n, err := r.r.Read(b)
if err != nil {
return n, err
}
// 2. Modify the n bytes currently stored in the buffer in place
for i := 0; i < n; i++ {
c := b[i]
// Handle uppercase letters
if c >= 'A' && c <= 'Z' {
b[i] = 'A' + (c-'A'+13)%26
} else if c >= 'a' && c <= 'z' { // Handle lowercase letters
b[i] = 'a' + (c-'a'+13)%26
}
}
// 3. Return the number of bytes modified and any error from the reader
return n, nil
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
output:
You cracked the code!
Images
Package image defines the Image interface:
package image
type Image interface {
ColorModel() color.Model
Bounds() Rectangle
At(x, y int) color.Color
}
Note: the Rectangle return value of the Bounds method is actually an image.Rectangle, as the declaration is inside package image.
(See the documentation for all the details.)
The color.Color and color.Model types are also interfaces, but we’ll ignore that by using the predefined implementations color.RGBA and color.RGBAModel. These interfaces and types are specified by the image/color package.
package main
import (
"fmt"
"image"
)
func main() {
// Allocate an in-memory 100x100 pixel canvas using an RGBA (Red, Green, Blue, Alpha) color model.
m := image.NewRGBA(image.Rect(0, 0, 100, 100))
// Print the outer boundaries of the canvas: the exact 2D rectangular grid coordinates where the image's pixels live.
fmt.Println(m.Bounds())
// Retrieves the color at the specific coordinate (0, 0).
// The .RGBA() method breaks it down into individual r, g, b, a values.
// Because a new image defaults to fully transparent black, this outputs 0 0 0 0.
fmt.Println(m.At(0, 0).RGBA())
}
output:
(0,0)-(100,100)
0 0 0 0
Exercise: Images
Remember the picture generator you wrote earlier? Let’s write another one, but this time it will return an implementation of image.Image instead of a slice of data.
Define your own Image type, implement the necessary methods, and call pic.ShowImage.
Bounds should return a image.Rectangle, like image.Rect(0, 0, w, h).
ColorModel should return color.RGBAModel.
At should return a color; the value v in the last picture generator corresponds to color.RGBA{v, v, 255, 255} in this one.
package main
import (
"image"
"image/color"
"golang.org/x/tour/pic"
)
// 1. Define the Image struct with width and height dimensions
type Image struct {
w, h int
}
// 2. Bounds returns the boundaries of the canvas
func (i Image) Bounds() image.Rectangle {
return image.Rect(0, 0, i.w, i.h)
}
// 3. ColorModel returns the standard RGBA color model
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
// 4. At calculates the color dynamically for each individual coordinate
func (i Image) At(x, y int) color.Color {
// Formula matching the logic of the earlier picture generator exercise
v := uint8(x ^ y)
return color.RGBA{v, v, 255, 255}
}
func main() {
// Create an instance of our image (e.g., 256x256 dimensions)
m := Image{w: 256, h: 256}
pic.ShowImage(m)
}
4. Generics
Generics
Type parameters
Go functions can be written to work on multiple types using type parameters. The type parameters of a function appear between brackets, before the function’s arguments.
func Index[T comparable](s []T, x T) int
This declaration means that s is a slice of any type T that fulfills the built-in constraint comparable. x is also a value of the same type.
comparable is a useful constraint that makes it possible to use the == and != operators on values of the type. In this example, we use it to compare a value to all slice elements until a match is found. This Index function works for any type that supports comparison.
package main
import "fmt"
// Index returns the index of x in s, or -1 if not found.
func Index[T comparable](s []T, x T) int {
for i, v := range s {
// v and x are type T, which has the comparable
// constraint, so we can use == here.
if v == x {
return i
}
}
return -1
}
func main() {
// Index works on a slice of ints
si := []int{10, 20, 15, -10}
fmt.Println(Index(si, 15))
// Index also works on a slice of strings
ss := []string{"foo", "bar", "baz"}
fmt.Println(Index(ss, "hello"))
}
output:
2
-1
Generic types
In addition to generic functions, Go also supports generic types. A type can be parameterized with a type parameter, which could be useful for implementing generic data structures.
This example demonstrates a simple type declaration for a singly-linked list holding any type of value.
As an exercise, add some functionality to this list implementation.
package main
import "fmt"
// List represents a singly-linked list that holds
// values of any type.
type List[T any] struct {
next *List[T]
val T
}
// Push adds a new value directly to the front of the list.
func (l *List[T]) Push(val T) {
newNode := &List[T]{val: val, next: l.next}
l.next = newNode
}
func main() {
// Create an integer list
numbers := List[int]{}
numbers.Push(10)
numbers.Push(20)
// Print the values
for curr := numbers.next; curr != nil; curr = curr.next {
fmt.Println(curr.val)
}
}
output:
20
10
5. Concurrency
Concurrency
Goroutines
A goroutine is a lightweight thread managed by the Go runtime.
go f(x, y, z)
starts a new goroutine running
f(x, y, z)
The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.
Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives, although you won’t need them much in Go as there are other primitives. (See the next slide.)
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
output:
world
hello
hello
world
world
hello
hello
world
world
hello
How it works:
func say(s string): This helper function runs a loop 5 times. In each turn, it pauses for 100 milliseconds and then prints the text we gave it.go say("world"): It tells Go to runsay("world")in the background (as a separate goroutine) and immediately move to the next line of code without waiting for it to finish.say("hello"): This runs normally on the main thread.
The outcome:
Because both tasks are running at the same time, their outputs will interleave. Instead of printing five “world”s followed by five “hello”s, you will see them mix together on the screen (e.g., hello, world, hello, world…).
As soon as the main thread finishes printing its five “hello”s, the program will terminate immediately, even if the background “world” thread hasn’t finished completely.
Channels
Channels are a typed conduit through which you can send and receive values with the channel operator, <-.
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
(The data flows in the direction of the arrow.)
Like maps and slices, channels must be created before use:
ch := make(chan int)
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
output:
-5 17 12
Buffered channels
Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:
ch := make(chan int, 100)
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
Modify the example to overfill the buffer and see what happens.
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
// without this line below, we get the resut:
// 1
// 2
// with the line below, we get an error
ch <- 3 // This overflows the buffer and blocks indefinitely!
fmt.Println(<-ch)
fmt.Println(<-ch)
}
output:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox1737369512/src/prog.go:9 +0x58
Why does this happen?
ch := make(chan int, 2)creates a channel that can hold at most 2 integers.ch <- 1andch <- 2successfully fill up the buffer.ch <- 3attempts to send a third value. Because the buffer is entirely full, this operation blocks the main goroutine, waiting for another goroutine to read from the channel and free up space.- Since no other goroutines exist to read from the channel, the main goroutine blocks forever. The Go runtime detects that no progress can ever be made and halts the program with a deadlock error.
Range and Close
A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after
v, ok := <-ch
ok is false if there are no more values to receive and the channel is closed.
The loop for i := range c receives values from the channel repeatedly until it is closed.
Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
Another note: Channels aren’t like files; you don’t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
output:
0
1
1
2
3
5
8
13
21
34
Select
The select statement lets a goroutine wait on multiple communication operations.
A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
output:
0
1
1
2
3
5
8
13
21
34
quit
Default Selection
The default case in a select is run if no other case is ready.
Use a default case to try a send or receive without blocking:
select {
case i := <-c:
// use i
default:
// receiving from c would block
}
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
tick := time.Tick(100 * time.Millisecond)
boom := time.After(500 * time.Millisecond)
elapsed := func() time.Duration {
return time.Since(start).Round(time.Millisecond)
}
for {
select {
case <-tick:
fmt.Printf("[%6s] tick.\n", elapsed())
case <-boom:
fmt.Printf("[%6s] BOOM!\n", elapsed())
return
default:
fmt.Printf("[%6s] .\n", elapsed())
time.Sleep(50 * time.Millisecond)
}
}
}
output:
[ 0s] .
[ 50ms] .
[ 100ms] tick.
[ 100ms] .
[ 150ms] .
[ 200ms] tick.
[ 200ms] .
[ 250ms] .
[ 300ms] tick.
[ 300ms] .
[ 350ms] .
[ 400ms] tick.
[ 400ms] .
[ 450ms] .
[ 500ms] tick.
[ 500ms] BOOM!
Exercise: Equivalent Binary Trees
There can be many different binary trees with the same sequence of values stored in it. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13.

A function to check whether two binary trees store the same sequence is quite complex in most languages. We’ll use Go’s concurrency and channels to write a simple solution.
This example uses the tree package, which defines the type:
type Tree struct {
Left *Tree
Value int
Right *Tree
}
Continue description on next page.
Exercise: Equivalent Binary Trees
-
Implement the
Walkfunction. -
Test the
Walkfunction.
The function tree.New(k) constructs a randomly-structured (but always sorted) binary tree holding the values k, 2k, 3k, …, 10k.
Create a new channel ch and kick off the walker:
go Walk(tree.New(1), ch)
Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, …, 10.
-
Implement the
Samefunction usingWalkto determine whethert1andt2store the same values. -
Test the
Samefunction.
Same(tree.New(1), tree.New(1)) should return true, and Same(tree.New(1), tree.New(2)) should return false.
The documentation for Tree can be found here.
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
var walk func(t *tree.Tree)
walk = func(t *tree.Tree) {
if t == nil {
return
}
// In-order traversal: Left, Node, Right
walk(t.Left)
ch <- t.Value
walk(t.Right)
}
walk(t)
close(ch) // Close channel to signal traversal is finished
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
// Run walkers concurrently
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
// If one channel closes early or values don't match
if ok1 != ok2 || v1 != v2 {
return false
}
// If both channels are closed and all values matched
if !ok1 {
break
}
}
return true
}
func main() {
// 1 & 2. Test the Walk function
ch := make(chan int)
go Walk(tree.New(1), ch)
fmt.Print("Walk(tree.New(1)): ")
for i := 0; i < 10; i++ {
fmt.Printf("%d ", <-ch)
}
fmt.Println()
// 3 & 4. Test the Same function
fmt.Printf("Same(tree.New(1), tree.New(1)): %v\n", Same(tree.New(1), tree.New(1)))
fmt.Printf("Same(tree.New(1), tree.New(2)): %v\n", Same(tree.New(1), tree.New(2)))
}
output:
Walk(tree.New(1)): 1 2 3 4 5 6 7 8 9 10
Same(tree.New(1), tree.New(1)): true
Same(tree.New(1), tree.New(2)): false
sync.Mutex
We’ve seen how channels are great for communication among goroutines.
But what if we don’t need communication? What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts?
This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex.
Go’s standard library provides mutual exclusion with sync.Mutex and its two methods:
Lock
Unlock
We can define a block of code to be executed in mutual exclusion by surrounding it with a call to Lock and Unlock as shown on the Inc method.
We can also use defer to ensure the mutex will be unlocked as in the Value method.
package main
import (
"fmt"
"sync"
"time"
)
// SafeCounter is safe to use concurrently.
type SafeCounter struct {
mu sync.Mutex
v map[string]int
}
// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}
// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
return c.v[key]
}
func main() {
c := SafeCounter{v: make(map[string]int)}
for i := 0; i < 1000; i++ {
go c.Inc("somekey")
}
time.Sleep(time.Second)
fmt.Println(c.Value("somekey"))
}
output:
1000
Exercise: Web Crawler
In this exercise you’ll use Go’s concurrency features to parallelize a web crawler.
Modify the Crawl function to fetch URLs in parallel without fetching the same URL twice.
Hint: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not safe for concurrent use!
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
// URLCache safely tracks visited URLs across concurrent goroutines.
type URLCache struct {
mu sync.Mutex
visited map[string]bool
}
// IsVisited checks if a URL has been seen. If not, it marks it as visited.
func (c *URLCache) IsVisited(url string) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.visited[url] {
return true
}
c.visited[url] = true
return false
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, cache *URLCache, wg *sync.WaitGroup) {
// Decrement the counter when the goroutine completes
defer wg.Done()
if depth <= 0 {
return
}
// Check and mark the URL thread-safely
if cache.IsVisited(url) {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
// Launch a new parallel goroutine for each found URL
for _, u := range urls {
wg.Add(1)
go Crawl(u, depth-1, fetcher, cache, wg)
}
}
func main() {
// Initialize our safe cache and wait group
cache := &URLCache{visited: make(map[string]bool)}
var wg sync.WaitGroup
// Bootstrap the crawler with the initial URL
wg.Add(1)
go Crawl("https://golang.org/", 4, fetcher, cache, &wg)
// Block main until all crawling work is finished
wg.Wait()
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
output:
found: https://golang.org/ "The Go Programming Language"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/ "Packages"
found: https://golang.org/pkg/os/ "Package os"
found: https://golang.org/pkg/fmt/ "Package fmt"
Privacy-First Subscription
Receive a notification in your inbox whenever I publish a new post. This is a reader-focused subscription loop built for absolute privacy: you stay in control, and I do not see, track, or collect your email address.
Follow via FeedRabbit