1. Lesson 1: Introduction, installation and first code¶
1.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!
1.2. Links, bibliography¶
- The Go Programming Language
- Install the Go tools
- Effective Go
- The Go Programming Language Specification
- Package Documentation
- 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
1.3. Installation¶
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 codebin: contains the generated binariespkg: 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.
1.4. First code¶
1.4.1. 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.
1.4.2. 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | package main
import (
"bufio"
"os"
"log"
"fmt"
"io/ioutil"
"encoding/json"
"strings"
)
var registry map[string]string
func loadRegistry() {
// retrieve location from environment variabel
registryFile := os.Getenv("BROCADE_REGISTRY")
if registryFile == "" {
log.Fatal("BROCADE_REGISTRY environment variable is not defined")
}
// read file
b, err := ioutil.ReadFile(registryFile)
if err != nil {
log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryFile), err)
}
// interpret JSON
err = json.Unmarshal(b, ®istry)
if err != nil {
log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryFile), err)
}
}
func main() {
// load registry
loadRegistry()
reader := bufio.NewReader(os.Stdin)
// loop and read until empty
for {
fmt.Print("Enter key: ")
key, err := reader.ReadString('\n')
if err != nil {
log.Fatal("Cannot read from stdin")
}
key = strings.TrimSpace(key)
if key == "" {
break
}
value, ok := registry[key]
if !ok {
value = "?"
}
fmt.Printf("%s -> %s\n\n", key, value)
}
}
|
Changing to the directory with delphi1.go
go build
go install
try it:
delphi1
1.4.2.1. 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 mainneeds afunc main() - Line 45: elegant and powerful way to code an infinite loop
1.4.2.2. Some experiments¶
insert a superfluous import and compile
1 2 3 4 5 6 7 8 9 10
import ( "bufio" "os" "log" "fmt" "crypto/aes" "io/ioutil" "encoding/json" "strings" )
remove
package mainremove
func main()
1.4.3. 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package registry
import (
"os"
"log"
"fmt"
"io/ioutil"
"encoding/json"
)
var Registry = loadRegistry()
func loadRegistry() (registry map[string]string) {
// retrieve location from environment variabel
registryFile := os.Getenv("BROCADE_REGISTRY")
if registryFile == "" {
log.Fatal("BROCADE_REGISTRY environment variable is not defined")
}
// read file
b, err := ioutil.ReadFile(registryFile)
if err != nil {
log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryFile), err)
}
// interpret JSON
err = json.Unmarshal(b, ®istry)
if err != nil {
log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryFile), err)
}
return
}
|
Changing to the directory with registry.go
go build
go install
1.4.3.1. 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 loadRegistryis defined with a named return value - Line 34: the naked
return, returnsregistry
1.4.3.2. 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package main
import (
"bufio"
"fmt"
"os"
"log"
"strings"
"brocade.be/rphilips/registry"
)
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter key: ")
key, err := reader.ReadString('\n')
if err != nil {
log.Fatal("Cannot read from stdin")
break;
}
key = strings.TrimSpace(key)
if key == "" {
break
}
value, ok := registry.Registry[key]
if !ok {
value = "?"
}
fmt.Printf("%s -> %s\n\n", key, value)
}
}
|
Changing to the directory with delphi2.go
go build
go install
try it:
delphi2
1.4.3.3. Notes¶
- Line 10: the
brocade.be/rphilips/registrylibrary is imported. The name registry and all its exported items (those starting with an uppercase) are available to our program - Line 28: the
registry.Registryis used
1.4.3.4. Some experiments¶
- change in
registry.go:var Registry map[string]stringtovar registry map[string]stringand compile
1.4.4. Solution 3¶
We can optimize this solution.
Change registry.go to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package registry
import (
"os"
"log"
"fmt"
"io/ioutil"
"encoding/json"
)
var Registry map[string]string
func init() {
registryFile := os.Getenv("BROCADE_REGISTRY")
if registryFile == "" {
log.Fatal("BROCADE_REGISTRY environment variable is not defined")
}
b, err := ioutil.ReadFile(registryFile)
if err != nil {
log.Fatal(fmt.Sprintf("Cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryFile), err)
}
err = json.Unmarshal(b, &Registry)
if err != nil {
log.Fatal(fmt.Sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryFile), err)
}
}
|
Changing to the directory with registry.go
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
1.4.4.1. Notes¶
- Line 14: the
func init()library is imported. There can be several of thosefunc 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.
1.4.4.2. Some experiments¶
- in
registry.go,var Registry map[string]stringafterinit(){...} - in
registry.go, put a secondinit(){...}afterinit(){...}
1.5. 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 permission:
chmod +x delphi2
and try it:
delphi2