Get Programming with Go.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Get Programming with Go Get Programming with Go Nathan Youngman Roger Peppé MANNING Shelter Island For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. The Go Gopher is © 2009 Renée French and used under Creative Commons Attributions 3.0 license. Original illustrations by Olga Shalakhina are © 2015 Olga Shalakhina and used by permission. Original illustrations by Erick Zelaya are © 2018 Erick Zelaya and used by permission. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Acquisition editor: Michael Stephens Development editors: Jenny Stout, Marina Michaels Technical development editors: Matthew Merkes, Joel Kotarski Review editor: Aleksandar Dragosavljevic´ Project editor: David Novak Copyeditor: Corbin Collins Proofreaders: Melody Dolab, Elizabeth Martin Technical proofreader: Christopher Haupt Typesetter: Dottie Marsico Graphics: Olga Shalakhina, Erick Zelaya, April Milne Cover designer: Monica Kamsvaag Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 ISBN 9781617293092 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – DP – 23 22 21 20 19 18 Contents Preface vii Acknowledgments viii About this book x About the authors xiii Unit 0 Lesson 14 First-class functions 108 Lesson 15 Capstone: Temperature tables 117 GETTING STARTED Unit 4 Lesson 1 Get ready, get set, Go 3 COLLECTIONS Unit 1 Lesson 16 Arrayed in splendor 121 Lesson 17 Slices: Windows into arrays 130 IMPERATIVE PROGRAMMING Lesson 18 A bigger slice 138 Lesson 2 A glorified calculator 13 Lesson 19 The ever-versatile map 146 Lesson 3 Loops and branches 23 Lesson 20 Capstone: A slice of life 155 Lesson 4 Variable scope 34 Lesson 5 Capstone: Ticket to Mars 41 Unit 5 Unit 2 STATE AND BEHAVIOR Lesson 21 A little structure 161 TYPES Lesson 22 Go’s got no class 170 Lesson 6 Real numbers 45 Lesson 23 Composition and forwarding 177 Lesson 7 Whole numbers 53 Lesson 24 Interfaces 186 Lesson 8 Big numbers 62 Lesson 25 Capstone: Martian animal Lesson 9 Multilingual text 68 sanctuary 196 Lesson 10 Converting between types 79 Lesson 11 Capstone: The Vigenère cipher 88 Unit 6 Unit 3 DOWN THE GOPHER HOLE Lesson 26 A few pointers 201 BUILDING BLOCKS Lesson 27 Much ado about nil 220 Lesson 12 Functions 93 Lesson 28 To err is human 230 Lesson 13 Methods 101 Lesson 29 Capstone: Sudoku rules 248 v vi Contents Unit 7 CONCURRENT PROGRAMMING Lesson 30 Goroutines and concurrency 253 Lesson 31 Concurrent state 269 Lesson 32 Capstone: Life on Mars 282 Conclusion Where to Go from here 285 Appendix Solutions 287 Index 339 Preface Everything changes and nothing remains still. —Heraclitus While traveling Europe in 2005, Nathan heard rumblings of a new web framework called Ruby on Rails. Returning to Alberta in time to celebrate Christmas, he found a copy of Agile Web Development with Rails (Pragmatic Bookshelf, 2005) at the computer bookstore downtown. Over the next two years, he transitioned his career from Cold- Fusion to Ruby. At university in York, England, Roger was introduced to the radical simplicity of Bell Labs Research UNIX and the Plan 9 OS produced by the same group, which included Go authors Rob Pike and Ken Thompson. Roger became a fan and later worked with the Inferno system, which used its own language, Limbo, a close ancestor of Go. In November 2009, Go was announced as an open source project. Roger immediately saw its potential and started using it, making contributions to its standard library and ecosystem. He remains delighted by Go’s success, now programs in Go full time, and runs a local Go meetup. Nathan watched Rob Pike’s tech talk announcing Go but didn’t give Go a serious look until 2011. When a coworker spoke highly of Go, Nathan decided to read through a rough cut of The Go Programming Language Phrasebook (Addison-Wesley Professional, 2012) over Christmas break. Over the next few years, he went from using Go on hobby projects and blogging about Go (nathany.com) to organizing a local Go meetup (edmontongo.org) and writing Go at work. There’s no end to learning in the world of computer science, where the tools and tech- niques are continuously changing and improving. Whether you have a degree in com- puter science or are just starting out, teaching yourself new skills is important. We hope this book serves you well as you learn the Go programming language. vii Acknowledgments What a privilege it has been to write this book and help you learn Go. Thank you for reading! These pages represent the efforts of many individuals, not merely the authors on the cover. First and foremost, we would like to thank our editors Jennifer Stout and Marina Michaels for providing valuable feedback and for continuing to push us little by little over the finish line. Also, thank you to Joel Kotarski and Matt Merkes for your spot-on technical editing, Christopher Haupt for technical proofing, and copyeditor Corbin Collins for improving our grammar and style. Our thanks go to Bert Bates and to series editors Dan Maharry and Elesha Hyde for the conversations and guidelines that helped shape Get Programming with Go. We would like to thank Olga Shalakhina and Erick Zelaya for the wonderful illustra- tions, Monica Kamsvaag for the cover design, April Milne for sprucing up our figures, and Renée French for giving Go the lighthearted mascot that we all love. A special thank you goes to Dan Allen for creating AsciiDoctor, the tool used to write this book, and for his ongoing support. This book wouldn’t be a reality without Marjan Bace, Matko Hrvatin, Mehmed Pasic, Rebecca Rinehart, Nicole Butterfield, Candace Gillhoolley, Ana Romac, Janet Vail, David Novak, Dottie Marsico, Melody Dolab, Elizabeth Martin, and the whole crew at Manning for getting Get Programming with Go into the hands of readers. Thanks also to Aleksandar Dragosavljević for getting this book to reviewers, and to all the reviewers for providing valuable feedback, including Brendan Ward, Charles Kevin, Doug Sparling, Esther Tsai, Gianluigi Spagnuolo, Jeff Smith, John Guthrie, Luca Cam- pobasso, Luis Gutierrez, Mario Carrion, Mikaël Dautrey, Nat Luengnaruemitchai, Nathan Farr, Nicholas Boers, Nicholas Land, Nitin Gode, Orlando Sánchez, Philippe Charrière, Rob Weber, Robin Percy, Steven Parr, Stuart Woodward, Tom Goodheard, viii Acknowledgments ix Ulises Flynn, and William E. Wheeler. We’d also like to thank all the early access readers who provided feedback through the forums. Finally, we would like to thank Michael Stephens for suggesting the crazy idea of writ- ing a book, and the Go community for creating a language and ecosystem that we’re excited to write about! Nathan Youngman Naturally, I need to thank my parents, without whom I wouldn’t be here today. Both of my parents encouraged me to pursue my interest in computer programming from an early age, providing books and courses and access to computers. In addition to the official reviewers, I would like to thank Matthias Stone for providing feedback on early drafts, and Terry Youngman for helping me brainstorm ideas. I also want to thank the Edmonton Go community for cheering me on, and my employer, Mark Madsen, for providing the flexibility to make this endeavor feasible. More than anyone else, I want to thank Roger Peppé for coming alongside me as coauthor. He shortened the long road ahead by writing unit 7, and gave the project a much needed bump in momentum. Roger Peppé Most of all, I’d like to thank my wife, Carmen, for her forbearance and support as I worked on this book when we could have been out walking in the hills. Many thanks also to Nathan Youngman and Manning for their trust in taking me on as coauthor and for their patience during the final stages of this book. About this book Who should read this book Go is suitable for programmers with a wide range of skill levels—a necessity for any large project. Being a relatively small language, with minimal syntax and few concep- tual hurdles, Go could be the next great language for beginners. Unfortunately, many resources for learning Go presume a working knowledge of the C programming language. Get Programming with Go exists to fill the gap for scripters, hob- byists, and newcomers looking for a direct path to Go. To make it easier to get started, every code listing and exercise in this book can run inside the Go Playground (play .golang.org), so there’s nothing to install! If you’ve ever used a scripting language like JavaScript, Lua, PHP, Perl, Python, or Ruby, you’re ready to learn Go.