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
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
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 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
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
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
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
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
try it: delphi2 Notes Line 10: the brocade.be/rphilips/registry library is imported. The name registry and all its exported 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 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 permission: chmod +x delphi2 and try it: 10 Chapter 1. Lesson 1: Introduction, installation and first code
delphi2 1.5. Whetting you appetite 11
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