THE WAY TO GO A Thorough Introduction to the Go Programming Language IVO BALBAERT The Way to Go Also by Ivo Balbaert: “Handboek Programmeren met Ruby en Rails.”, 2009, Van Duuren Media, ISBN: 978-90-5940-365-9 The Way to Go A Thorough Introduction to the Go Programming Language Ivo Balbaert iUniverse, Inc Bloomington The Way to Go A Thorough Introduction to the Go Programming Language Copyright © 2012 by Ivo Balbaert All rights reserved No part of this book may be used or reproduced by any means, graphic, electronic, or mechanical, including photocopying, recording, taping or by any information storage retrieval system without the written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews iUniverse books may be ordered through booksellers or by contacting: iUniverse 1663 Liberty Drive Bloomington, IN 47403 www.iuniverse.com 1-800-Authors (1-800-288-4677) Because of the dynamic nature of the Internet, any web addresses or links contained in this book may have changed since publication and may no longer be valid The views expressed in this work are solely those of the author and not necessarily reflect the views of the publisher, and the publisher hereby disclaims any responsibility for them Any people depicted in stock imagery provided by Thinkstock are models, and such images are being used for illustrative purposes only Certain stock imagery © Thinkstock ISBN: 978-1-4697-6916-5 (sc) ISBN: 978-1-4697-6917-2 (ebk) Printed in the United States of America iUniverse rev date: 03/05/2012 Contents Preface xix PART 1—WHY LEARN GO—GETTING STARTED Chapter 1—Origins, Context and Popularity of Go .1 1.1 Origins and evolution 1.2 Main characteristics, context and reasons for developing a new language 1.2.1 Languages that influenced Go .4 1.2.2 Why a new language? 1.2.3 Targets of the language 1.2.4 Guiding design principles .7 1.2.5 Characteristics of the language 1.2.6 Uses of the language 1.2.7 Missing features? 1.2.8 Programming in Go 10 1.2.9 Summary 10 Chapter 2—Installation and Runtime Environment 11 2.1 Platforms and architectures 11 (1) The gc Go-compilers: 11 (2) The gccgo-compiler: 13 (3) File extensions and packages: .14 2.2 Go Environment variables 14 2.3 Installing Go on a Linux system .16 2.4 Installing Go on an OS X system 21 2.5 Installing Go on a Windows system .21 2.6 What is installed on your machine? 26 2.7 The Go runtime .27 2.8 A Go interpreter 27 Chapter 3—Editors, IDE’s and Other tools .28 3.1 Basic requirements for a decent Go development environment .28 3.2 Editors and Integrated Development Environments .29 3.2.1 Golang LiteIDE 32 3.2.2 GoClipse 33 3.3 Debuggers 34 3.4 Building and running go-programs with command- and Makefiles 35 3.5 Formatting code: go fmt or gofmt 39 3.6 Documenting code: go doc or godoc 40 3.7 Other tools .41 3.8 Go’s performance 41 3.9 Interaction with other languages .43 3.9.1 Interacting with C 43 3.9.2 Interacting with C++ 45 PART 2—CORE CONSTRUCTS AND TECHNIQUES OF THE LANGUAGE Chapter 4—Basic constructs and elementary data types .49 4.1 Filenames—Keywords—Identifiers 49 4.2 Basic structure and components of a Go-program 50 4.2.1 Packages, import and visibility 51 4.2.3 Comments 56 4.2.4 Types 57 4.2.5 General structure of a Go-program .58 4.2.6 Conversions 60 4.2.7 About naming things in Go 60 4.3 Constants 60 4.4 Variables 63 4.4.1 Introduction .63 4.4.2 Value types and reference types 66 4.4.3 Printing 68 4.4.4 Short form with the := assignment operator 69 4.4.5 Init-functions 70 4.5 Elementary types and operators .73 4.5.1 Boolean type bool 73 4.5.2 Numerical types 75 4.5.2.1 ints and floats 75 4.5.2.2 Complex numbers 79 4.5.2.3 Bit operators 79 4.5.2.4 Logical operators 81 4.5.2.5 Arithmetic operators .82 4.5.2.6 Random numbers 82 4.5.3 Operators and precedence 84 4.5.4 Aliasing types .84 4.5.5 Character type 85 4.6 Strings 86 4.7 The strings and strconv package 88 4.7.1—Prefixes and suffixes: 88 4.7.2—Testing whether a string contains a substring: 89 4.7.3—Indicating at which position (index) a substring or character occurs in a string: 89 4.7.4—Replacing a substring: 90 4.7.5—Counting occurrences of a substring: 90 4.7.6—Repeating a string: 90 4.7.7—Changing the case of a string: 91 4.7.8—Trimming a string: 92 4.7.9—Splitting a string: 92 4.7.10—Joining over a slice: 92 4.7.11—Reading from a string: 93 4.8 Times and dates .95 4.9 Pointers 96 Chapter 5—Control structures 101 5.1—The if else construct 101 5.2—Testing for errors on functions with multiple return values 106 5.3—The switch keyword 110 5.4—The for construct 114 5.4.1 Counter-controlled iteration .114 Character on position is: 116 5.4.2 Condition-controlled iteration 117 5.4.3 Infinite loops .118 5.4.4 The for range construct .119 5.5—Break / continue 121 5.6—Use of labels with break and continue—goto .123 Chapter 6—Functions .126 6.1 Introduction 126 6.2 Parameters and return values 129 6.2.1 Call by value / Call by reference 129 6.2.2 Named return variables .131 6.2.3 Blank identifier 133 6.2.4 Changing an outside variable 134 6.3 Passing a variable number of parameters .135 6.4 Defer and tracing 137 6.5 Built-in functions 142 6.6 Recursive functions 143 6.8 Closures (function literals) 147 6.9 Applying closures: a function returning another function 150 6.10 Debugging with closures 153 6.11 Timing a function .154 6.12 Using memoization for performance 154 Chapter 7—Arrays and Slices 157 7.1 Declaration and initialization .157 7.1.1 Concept 157 7.1.2 Array literals 161 7.1.3 Multidimensional arrays 162 7.1.4 Passing an array to a function 163 7.2 Slices 164 7.2.1 Concept 164 7.2.2 Passing a slice to a function .168 7.2.3 Creating a slice with make() 168 7.2.4 Difference between new() and make() .170 7.2.5 Multidimensional slices .171 7.2.6 The bytes package .171 7.3 For range construct 172 7.4 Reslicing .175 7.5 Copying and appending slices 176 7.6 Applying strings, arrays and slices 178 7.6.1 Making a slice of bytes from a string 178 7.6.2 Making a substring of a string 179 7.6.3 Memory representation of a string and a slice 179 7.6.4 Changing a character in a string 180 7.6.5 Comparison function for byte arrays 180 7.6.6 Searching and sorting slices and arrays .181 7.6.7 Simulating operations with append 182 7.6.8 Slices and garbage collection .182 Chapter 8—Maps 185 8.1 Declaration, initialization and make .185 8.1.1 Concept 185 8.1.2 Map capacity 188 8.1.3 Slices as map values 188 8.2 Testing if a key-value item exists in a map—Deleting an element 188 8.3 The for range construct 190 8.4 A slice of maps 191 8.5 Sorting a map .192 8.6 Inverting a map 194 Chapter 9—Packages .196 A The standard library 196 9.1 Overview of the standard library 196 9.2 The regexp package 199 9.3 Locking and the sync package 200 9.4 Accurate computations and the big package 202 B Custom and external packages: use, build, test, document, install 203 9.5 Custom packages and visibility .203 9.6 Using godoc for your custom packages 208 9.7 Using go install for installing custom packages .210 9.8 Custom packages: map structure, go install and go test 212 9.8.1 Map-structure for custom packages 212 9.8.2 Locally installing the package 215 9.8.3 OS dependent code 216 9.9 Using git for distribution and installation .216 9.9.1 Installing to github 216 9.9.2 Installing from github .217 9.10 Go external packages and projects 218 9.11 Using an external library in a Go program 219 Chapter 10—Structs and Methods 224 10.1 Definition of a struct 224 10.2 Creating a struct variable with a Factory method 232 10.2.1 A factory for structs 232 10.2.2 new() and make() revisited for maps and structs: .234 10.3 Custom package using structs .235 10.4 Structs with tags 236 10.5 Anonymous fields and embedded structs 237 10.5.1 Definition .237 Ivo Balbaert Question 14.1: Use a buffered channel throttle and a NewTicker object tick: import “time” rate_per_sec := 10 burst_limit := 100 tick := time.NewTicker(1e9 / rate_per_sec) defer tick.Stop() throttle := make(chan int64, burst_limit) go func() { for ns := range tick { select { case: throttle