PDF and Epub Files Available? You Can Upgrade to the Ebook Version at And, As a Print Book Customer, You Are Entitled to a Discount on the Ebook Copy
Total Page:16
File Type:pdf, Size:1020Kb
Mastering Go Second Edition Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures Mihalis Tsoukalos BIRMINGHAM - MUMBAI Mastering Go Second Edition Copyright © 2019 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Acquisition Editor: Andrew Waldron Acquisition Editor – Peer Reviews: Suresh Jain Project Editor: Kishor Rit Development Editor: Joanne Lovell Technical Editor: Aniket Shetty Copy Editor: Safis Editing Proofreader: Safis Editing Indexer: Pratik Shirodkar Production Designer: Sandip Tadge First published: April 2018 Second edition: August 2019 Production reference: 1270819 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-83855-933-5 www.packtpub.com Packt.com Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Fully searchable for easy access to vital information Copy and paste, print, and bookmark content Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Contributors About the author Mihalis Tsoukalos is a UNIX administrator, a programmer, a DBA, and a mathematician who enjoys writing technical books and articles and learning new things. He is the author of Go Systems Programming and Mastering Go. He has written more than 250 technical articles for many magazines, including Sys Admin, MacTech, Linux User and Developer, Usenix ;login:, Linux Format, and Linux Journal. His research interests include databases, visualization, statistics and machine learning. You can reach him at https://www.mtsoukalos.eu/ and @mactsouk. Mihalis is also a photographer. I would like to thank the people at Packt Publishing for helping me to write this book, including my technical reviewer, Mat Ryer, and Kishor Rit for answering all my questions and encouraging me during the whole process. I would like to dedicate this book to the loving memory of my parents, Ioannis and Argetta. About the reviewer Mat Ryer has been programming computers since he was six years old. He would build games and programs, first in BASIC on a ZX Spectrum, and then in AmigaBASIC and AMOS on Commodore Amiga with his father. Many hours were spent manually copying the code from the Amiga Format magazine and tweaking variables or moving GOTO statements around to see what might happen. The same spirit of exploration and obsession with programming led Mat to starting work with a local agency in Mansfield, England, when he was 18, where he started to build websites and other online services. After several years of working with various technologies and industries in London and around the world, Mat noticed a new systems language called Go that Google was pioneering. Since it addressed very pertinent and relevant modern technical challenges, he started using it to solve problems while the language was still in the beta stage, and he has been using it ever since. Mat contributes to open-source projects and has founded Go packages, including Testify, Moq, Silk, and Is, as well as a macOS developer tool called BitBar. In 2018, Mat co-founded Machine Box and still spends a lot of time speaking at conferences, writing about Go on his blog, and being an active member of the Go community. Table of Contents Chapter 1: Go and the Operating System 8 The history of Go 8 Where is Go going? 9 The advantages of Go 9 Is Go perfect? 10 What is a preprocessor? 11 The godoc utility 11 Compiling Go code 12 Executing Go code 13 Two Go rules 14 You either use a Go package or you do not include it 14 There is only one way to format curly braces 16 Downloading Go packages 17 UNIX stdin, stdout, and stderr 18 About printing output 19 Using standard output 21 Getting user input 23 About := and = 23 Reading from standard input 24 Working with command-line arguments 25 About error output 28 Writing to log files 30 Logging levels 30 Logging facilities 30 Log servers 31 A Go program that sends information to log files 32 About log.Fatal() 35 About log.Panic() 35 Writing to a custom log file 37 Printing line numbers in log entries 39 Error handling in Go 41 The error data type 41 Error handling 43 Using Docker 46 Exercises and links 51 Summary 52 Chapter 2: Understanding Go Internals 53 The Go compiler 54 Table of Contents Garbage collection 55 The tricolor algorithm 58 More about the operation of the Go garbage collector 61 Maps, slices, and the Go garbage collector 62 Using a slice 63 Using a map with pointers 63 Using a map without pointers 64 Splitting the map 65 Comparing the performance of the presented techniques 65 Unsafe code 66 About the unsafe package 68 Another example of the unsafe package 69 Calling C code from Go 70 Calling C code from Go using the same file 70 Calling C code from Go using separate files 71 The C code 72 The Go code 72 Mixing Go and C code 74 Calling Go functions from C code 75 The Go package 75 The C code 76 The defer keyword 77 Using defer for logging 80 Panic and recover 82 Using the panic function on its own 84 Two handy UNIX utilities 85 The strace tool 85 The dtrace tool 86 Your Go environment 88 The go env command 90 The Go assembler 91 Node trees 92 Finding out more about go build 98 Creating WebAssembly code 100 A quick introduction to WebAssembly 100 Why is WebAssembly important? 100 Go and WebAssembly 100 An example 101 Using the generated WebAssembly code 102 General Go coding advice 104 Exercises and links 104 Summary 105 Chapter 3: Working with Basic Go Data Types 107 Numeric data types 108 [ ii ] Table of Contents Integers 108 Floating-point numbers 108 Complex numbers 108 Number literals in Go 2 111 Go loops 111 The for loop 111 The while loop 112 The range keyword 113 An example with multiple Go loops 113 Go arrays 115 Multi-dimensional arrays 116 The shortcomings of Go arrays 118 Go slices 119 Performing basic operations on slices 119 Slices are expanded automatically 121 Byte slices 123 The copy() function 123 Multi-dimensional slices 125 Another example with slices 126 Sorting slices using sort.Slice() 128 Appending an array to a slice 130 Go maps 131 Storing to a nil map 133 When you should use a map 134 Go constants 134 The constant generator iota 136 Go pointers 139 Why use pointers? 142 Times and dates 142 Working with times 144 Parsing times 144 Working with dates 146 Parsing dates 146 Changing date and time formats 147 Measuring execution time 149 Measuring the operation of the Go garbage collector 151 Web links and exercises 151 Summary 152 Chapter 4: The Uses of Composite Types 153 About composite types 154 Structures 154 Pointers to structures 156 Using the new keyword 158 Tuples 159 [ iii ] Table of Contents Regular expressions and pattern matching 160 Introducing some theory 161 A simple example 161 A more advanced example 164 Matching IPv4 addresses 167 Strings 171 What is a rune? 174 The unicode package 176 The strings package 177 The switch statement 181 Calculating Pi with high accuracy 185 Developing a key-value store in Go 187 Go and the JSON format 193 Reading JSON data 193 Saving JSON data 195 Using Marshal() and Unmarshal() 197 Parsing JSON data 198 Go and XML 201 Reading an XML file 204 Customizing XML output 206 Go and the YAML format 207 Additional resources 208 Exercises and web links 208 Summary 209 Chapter 5: How to Enhance Go Code with Data Structures 210 About graphs and nodes 211 Algorithm complexity 211 Binary trees in Go 212 Implementing a binary tree in Go 213 Advantages of binary trees 215 Hash tables in Go 216 Implementing a hash table in Go 217 Implementing the lookup functionality 219 Advantages of hash tables 220 Linked lists in Go 220 Implementing a linked list in Go 222 Advantages of linked lists 225 Doubly linked lists in Go 226 Implementing a doubly linked list in Go 227 Advantages of doubly linked lists 230 Queues in Go 231 Implementing a queue in Go 231 Stacks in Go