Go Tutorial PDF
Go Tutorial PDF
Release latest
i
ii
go-tutorial Documentation, Release latest
Contents:
This tutorial approach to the Go programming language is higly personal: it handles the questions I ask myself when
I study a new programming language. It works for me, let us hope it works for you as well.
The emphasis is not so much on syntax but on answering questions, big and small, which cross my mind when I am
learning and - when left unanswered - prevent me to work well with the language.
Contents 1
go-tutorial Documentation, Release latest
2 Contents
CHAPTER 1
Introduction
This tutorial approach to the Go programming language is higly personal: it handles the questions I ask myself when
I study a new programming language. It works for me, let us hope it works for you as well.
The emphasis is not so much on syntax but on answering questions, big and small, which cross my mind when I am
learning and - when left unanswered - prevent me to work well with the language.
Why should you learn Go ?
Strangely enough, a tutorial, pretending to be big on answering questions, does not answer the very first one. I think,
if you want to spend your time on learning a new language, you are likely to know the answer already. Moreover, as
a side-effect of going through this tutorial, you will certainly note the ease with which Go handles concurrency, the
quality of the tool set and the backwards compatibility of the language.
This tutorial assumes you are already familiar with a programming language. Knowledge of Python would be a good
basis to start this tutorial but others work as well.
Note: I do not think that Go is a replacement of Python: changing Python for Go is like replacing a commuter’s
bicycle with a racing bicycle: only in particular circumstances a good idea!
Links, bibliography
3
go-tutorial Documentation, Release latest
• Go in Action / William Kennedy with Brian Ketelsen and Erik St. Martin, Foreword by Steve Francia, November
2015 - ISBN 9781617291784 - 264 pages
• Programming in Go: Creating Applications for the 21st Century / Mark Summerfield - Published May 4, 2012
by Addison-Wesley Professional - ISBN 0-321-77463-9
• Go Programming Language, The / Alan A. A. Donovan, Brian W. Kernighan - Published Nov 16, 2015 by
Addison-Wesley Professional - ISBN 0-13-419058-0
Installation
Warning: Make the distinction between the Go specification and the workings of the Go tools which are installed
on your computer.
Working with the standard Go tools comes with a price: you develop your source code according to the way the Go
designers intended it: you organise the code in a workspace.
This workspace presents itself as a directory in your home directory with a standard name go. This directory contains
the sub-directories:
• src: contains the source code
• bin: contains the generated binaries
• pkg: contains the compiled libraries
Make sure that the directory containing the go binary is in your PATH
Then:
go env
Note the value associated with GOPATH and make a subdirectory bin in that directory. Put this new directory also in
your PATH
Later we will come back to these directories and environment variables.
First code
Project
The environment variable BROCADE_REGISTRY holds the name of a JSON file containing a simple key/value store.
These are properties to use in your software: instead of hard-coding a value, we use a key (consisting of lowercase
ASCII, digits and a MINUS symbol) that we associate with an actual value.
In this project we will build a simple go based software which can query this key/value store.
Solution 1
In the subdirectory src of GOPATH, make a directory brocade.be, and here a sub-directory rphilips (user your
own userid).
Finally, another directory delphi1
In this directory, create a file delphi1.go:
1 package main
2
3 import (
4 "bufio"
5 "os"
6 "log"
7 "fmt"
8 "io/ioutil"
9 "encoding/json"
10 "strings"
11 )
12
15
16 func loadRegistry() {
17 // retrieve location from environment variabel
18 registryFile := os.Getenv("BROCADE_REGISTRY")
19 if registryFile == "" {
20 log.Fatal("BROCADE_REGISTRY environment variable is not defined")
21 }
22
23 // read file
24 b, err := ioutil.ReadFile(registryFile)
25 if err != nil {
26 log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment
˓→variable)\n", registryFile), err)
27 }
28
29 // interpret JSON
30 err = json.Unmarshal(b, ®istry)
31 if err != nil {
32 log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse
˓→http://jsonlint.com/\n", registryFile), err)
33 }
34 }
35
36
37 func main() {
38
39 // load registry
40 loadRegistry()
41
42 reader := bufio.NewReader(os.Stdin)
43
62 }
go build
go install
try it:
delphi1
Notes
• Line 1: Every Go file contains a package statement. The main package is used for executables
• Line 3: Import statement. The corresponding packages can be referenced by the last part of the impart string
• Line 13: Go is statically typed and compiled, so the type of every value has to be known at compile time. In Go,
evry variable is initialised, even it is silent.
• Line 16: the basic structuring component is the function.
• Line 18: note how a name is referenced
• Line 24: Functions can return multiple values, the receiving and of the application has to ‘capture’ as many
values as are returned
• Line 30: Go can work with pointers without the drawback of the C language
• Line 37: package main needs a func main()
• Line 45: elegant and powerful way to code an infinite loop
Some experiments
1 import (
2 "bufio"
3 "os"
4 "log"
5 "fmt"
6 "crypto/aes"
7 "io/ioutil"
8 "encoding/json"
9 "strings"
10 )
Solution 2
The previous solution does not allow for re-use: every application which needs the registry has to implement its own
loadRegistry()
So, let us create a new directory: src/brocade.be/rphilips/registry and put a file registry.go:
1 package registry
2
3 import (
4 "os"
5 "log"
6 "fmt"
7 "io/ioutil"
8 "encoding/json"
9 )
10
15
22 // read file
23 b, err := ioutil.ReadFile(registryFile)
24 if err != nil {
25 log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment
˓→variable)\n", registryFile), err)
26 }
27
28 // interpret JSON
29 err = json.Unmarshal(b, ®istry)
30 if err != nil {
31 log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse
˓→http://jsonlint.com/\n", registryFile), err)
32 }
33
34 return
35 }
go build
go install
Notes
• Line 1: the first line is the required package statement. The name of a registry is alsways an identifier and, by
convention, lowercase
• Line 11: a name of a variable is intoduced here.
• Line 13: func loadRegistry is defined with a named return value
• Line 34: the naked return, returns registry
Some experiments
1 package main
2
3 import (
4 "bufio"
5 "fmt"
6 "os"
7 "log"
8 "strings"
9
10 "brocade.be/rphilips/registry"
11 )
12
13 func main() {
14
15 reader := bufio.NewReader(os.Stdin)
16
17 for {
18 fmt.Print("Enter key: ")
19 key, err := reader.ReadString('\n')
20 if err != nil {
21 log.Fatal("Cannot read from stdin")
22 break;
23 }
24 key = strings.TrimSpace(key)
25 if key == "" {
26 break
27 }
28 value, ok := registry.Registry[key]
29 if !ok {
30 value = "?"
31 }
32 fmt.Printf("%s -> %s\n\n", key, value)
33 }
34 }
go build
go install
try it:
delphi2
Notes
• Line 10: the brocade.be/rphilips/registry library is imported. The name registry and all its ex-
ported items (those starting with an uppercase) are available to our program
• Line 28: the registry.Registry is used
Some experiments
Solution 3
1 package registry
2
3 import (
4 "os"
5 "log"
6 "fmt"
7 "io/ioutil"
8 "encoding/json"
9 )
10
13
14 func init() {
15 registryFile := os.Getenv("BROCADE_REGISTRY")
16 if registryFile == "" {
17 log.Fatal("BROCADE_REGISTRY environment variable is not defined")
18 }
19 b, err := ioutil.ReadFile(registryFile)
20 if err != nil {
21 log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment
˓→variable)\n", registryFile), err)
22 }
23 err = json.Unmarshal(b, &Registry)
24 if err != nil {
25 log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse
˓→http://jsonlint.com/\n", registryFile), err)
26 }
27
28 }
go build
go install
go build
go install
go build
go install
try it:
delphi2
Notes
• Line 14: the func init() library is imported. There can be several of those func init() in a package
(even in the same file). These functions have no arguments and no return values. But they are executed the
moment their package is imported.
Some experiments
For OSX:
For linux:
and transfer the binary to an appropriate machine. Is this a UNIX machine, do not forget to set the execution permis-
sion:
chmod +x delphi2
delphi2
B
BROCADE_REGISTRY, 4
E
environment variable
BROCADE_REGISTRY, 4
GOPATH, 4, 5
PATH, 4
G
GOPATH, 4, 5
P
PATH, 4
13