Programming in Go
Creating Applications for the 21st Century
Mark Summerfield
Upper Saddle River, NJ Boston Indianapolis San Francisco
New York Toronto Montreal London Munich Paris Madrid
Capetown Sydney Tokyo Singapore Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
For sales outside the United States, please contact:
International Sales
Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data
Summerfield, Mark.
Programming in Go : creating applications for the 21st century / Mark Summerfield.
p.cm.
Includes bibliographical references and index.
ISBN 978-0-321-77463-7 (pbk. : alk. paper)
1. Go (Computer program language) 2. Computer programming 3. Application software
Development I. Title.
QA76.73.G63S86 2012
005.133dc23
2012001914
Copyright 2012 Qtrac Ltd.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-321-77463-7
ISBN-10: 0-321-77463-9
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, April 2012
This book is dedicated to
Jasmin Blanchette and Trenton Schulz
Tables
Introduction
The purpose of this book is to teach solid idiomatic Go programming using all the features the language provides, as well as the most commonly used Go packages from Gos standard library. The book is also designed to serve as a useful reference once the language is learned. To meet both of these goals the book is quite comprehensive and tries to cover every topic in just one placeand with forward and backward cross-references throughout.
Go is quite C-like in spirit, being a small and efficient language with convenient low-level facilities such as pointers. Yet Go also offers many features associated with high- or very high-level languages, such as Unicode strings, powerful built-in data structures, duck typing, garbage collection, and high-level concurrency support that uses communication rather than shared data and locks. Go also has a large and wide-ranging standard library.
The reader is assumed to have programming experience in a mainstream programming language such as C, C++, Java, Python, or similar, although all of Gos unique features and idioms are illustrated with complete runnable examples that are fully explained in the text.
To successfully learn any programming language it is necessary to write programs in that language. To this end the books approach is wholly practical, and readers are encouraged to experiment with the examples, try the exercises, and write their own programs to get hands-on experience. As with all my previous books, the quoted code snippets are of live code; that is, the code was automatically extracted from .go
source files and directly embedded in the PDF that went to the publisherso there are no cut and paste errors, and the code works. Wherever possible, small but complete programs and packages are used as examples to provide realistic use cases. The examples, exercises, and solutions are available online at www.qtrac.eu/gobook.html.
The books key aim is to teach the Go language, and although many of the standard Go packages are used, not all of them are. This is not a problem, since reading the book will provide enough Go knowledge for readers to be able to make use of any of the standard packages, or any third-party Go package, and of course, be able to create their own packages.
Why Go?
The Go programming language began as an internal Google project in 2007. The original design was by Robert Griesemer and Unix luminaries Rob Pike and Ken Thompson. On November 10, 2009, Go was publicly unveiled under a liberal open source license. Go is being developed by a team at Google which includes the original designers plus Russ Cox, Andrew Gerrand, Ian Lance Taylor, and many others. Go has an open development model and many developers from around the world contribute to it, with some so trusted and respected that they have the same commit privileges as the Googlers. In addition, many third-party Go packages are available from the Go Dashboard (godashboard.appspot.com/project).
Go is the most exciting new mainstream language to appear in at least 15 years and is the first such language that is aimed squarely at 21st century computersand their programmers.
Go is designed to scale efficiently so that it can be used to build very big applicationsand to compile even a large program in mere seconds on a single computer. The lightning-fast compilation speed is made possible to a small extent because the language is easy to parse, but mostly because of its dependency management. If file app.go depends on file pkg1.go , which in turn depends on pkg2.go , in a conventional compiled language app.go would need both pkg1.go s and pkg2.go s object files. But in Go, everything that pkg2.go exports is cached in pkg1.go s object file, so pkg1.go s object file alone is sufficient to build app.go . For just three files this hardly matters, but it results in huge speedups for large applications with lots of dependencies.
Since Go programs are so fast to build, it is practical to use them in situations where scripting languages are normally used (see the sidebar ). Furthermore, Go can be used to build web applications using Googles App Engine.
Go uses a very clean and easy-to-understand syntax that avoids the complexity and verbosity of older languages like C++ (first released in 1983) or Java (first released in 1995). And Go is a strongly statically typed language, something which many programmers regard as essential for writing large programs. Yet Gos typing is not burdensome due to Gos short declare and initialize variable declaration syntax (where the compiler deduces the type so it doesnt have to be written explicitly), and because Go supports a powerful and convenient version of duck typing.
Languages like C and C++ require programmers to do a vast amount of bookkeeping when it comes to memory managementbookkeeping that could be done by the computer itself, especially for concurrent programs where keeping track can be fiendishly complicated. In recent years C++ has greatly improved in this area with various smart pointers, but is only just catching up with Java with regard to its threading library. Java relieves the programmer from the burden of memory management by using a garbage collector. C has only third-party threading libraries, although C++ now has a standard threading library. However, writing concurrent programs in C, C++, or Java requires considerable bookkeeping by programmers to make sure they lock and unlock resources at the right times.