go-tutorial Documentation
Release latest
Jun 04, 2017
Contents
1 Lesson 1: Introduction, installation and first code 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Links, bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 First code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.1 Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.2 Solution 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.3 Solution 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.4 Solution 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Whetting you appetite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
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
Lesson 1: Introduction, installation and first code
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
• The Go Programming Language
• Install the Go tools
• Effective Go
• The Go Programming Language Specification
• Package Documentation
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
The Go Programming Language
This tutorial handles Go 1.8+
Go is a pragmatic language: it tries to circumvent all kinds of essentially meaningless discussions (e.g. “Where to
place { and } in the code).
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.
4 Chapter 1. Lesson 1: Introduction, installation and first code
go-tutorial Documentation, Release latest
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
13 var registry map[string]string
14
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
44 // loop and read until empty
45 for {
46 fmt.Print("Enter key: ")
47 key, err := reader.ReadString('\n')
48 if err != nil {
1.4. First code 5
go-tutorial Documentation, Release latest
49 log.Fatal("Cannot read from stdin")
50 }
51 key = strings.TrimSpace(key)
52 if key == "" {
53 break
54 }
55 value, ok := registry[key]
56 if !ok {
57 value = "?"
58 }
59 fmt.Printf("%s -> %s\n\n", key, value)
60 }
61
62 }
Changing to the directory with delphi1.go
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
• insert a superfluous import and compile
1 import (
2 "bufio"
3 "os"
4 "log"
5 "fmt"
6 "crypto/aes"
7 "io/ioutil"
8 "encoding/json"
6 Chapter 1. Lesson 1: Introduction, installation and first code
go-tutorial Documentation, Release latest
9 "strings"
10 )
• remove package main
• remove func main()
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
11 var Registry = loadRegistry()
12
13 func loadRegistry() (registry map[string]string) {
14
15
16 // retrieve location from environment variabel
17 registryFile := os.Getenv("BROCADE_REGISTRY")
18 if registryFile == "" {
19 log.Fatal("BROCADE_REGISTRY environment variable is not defined")
20 }
21
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 }
Changing to the directory with registry.go
go build
go install
1.4. First code 7
go-tutorial Documentation, Release latest
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
• remove package registry
• note the naked return
Finally, let us create a directory: src/brocade.be/rphilips/delphi2 and put a file delphi2.go:
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 }
Changing to the directory with delphi2.go
go build
go install
8 Chapter 1. Lesson 1: Introduction, installation and first code
go-tutorial Documentation, Release latest
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
• change in registry.go: var Registry map[string]string to var registry
map[string]string and compile
Solution 3
We can optimize this solution.
Change registry.go to:
1 package registry
2
3 import (
4 "os"
5 "log"
6 "fmt"
7 "io/ioutil"
8 "encoding/json"
9 )
10
11 var Registry map[string]string
12
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 }
Changing to the directory with registry.go
1.4. First code 9
go-tutorial Documentation, Release latest
go build
go install
Changing to the directory with delphi2.go
go build
go install
Changing to the directory with registry.go
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
• in registry.go, var Registry map[string]string after init(){...}
• in registry.go, put a second init(){...} after init(){...}
Whetting you appetite
Changing to the directory with delphi2.go, chose your poison:
For MS-Windows:
GOOS=windows GOARCH=amd64 go build
For OSX:
GOOS=darwin GOARCH=amd64 go build
For linux:
GOOS=linux GOARCH=amd64 go build
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
and try it:
10 Chapter 1. Lesson 1: Introduction, installation and first code
go-tutorial Documentation, Release latest
delphi2
1.5. Whetting you appetite 11
go-tutorial Documentation, Release latest
12 Chapter 1. Lesson 1: Introduction, installation and first code
Index
B
BROCADE_REGISTRY, 4
E
environment variable
BROCADE_REGISTRY, 4
GOPATH, 4, 5
PATH, 4
G
GOPATH, 4, 5
P
PATH, 4
13