benchmarks, examples, platfor m-specific var iants, and documentation for a Fo llow the ins tructions at https://golang org/doc/install if the go to ol on your com-
Previous PDF | Next PDF |
[PDF] PDF form - Go Resources
folder named ~/Go/src/golang-book/chapter2 but this documentation can be difficult to understand Back to the function at hand, this documentation is
[PDF] Book - The Go Programming Language
benchmarks, examples, platfor m-specific var iants, and documentation for a Fo llow the ins tructions at https://golang org/doc/install if the go to ol on your com-
[PDF] Preview Go Tutorial (PDF Version) - Tutorialspoint
About the Tutorial Go language is a programming language initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson
[PDF] Learning Go - Miek Gieben
There is already a substantial amount of documentation written about Go ahttp ://golang org/doc/ itself is served by go doc {G}oCourseDay2 pdf , 2010
[PDF] The Go Programming Language
Keys to success: – Simplicity and elegance – Availability – Performance • No more manual assembly code – Documentation Brian Kernighan Dennis Ritchie
[PDF] go-pdf - Karl Seguin
book for a couple reasons The first is that Go's own documentation, in particular Effective You can head over to https://golang org/pkg/ · fmt/#Println to learn
[PDF] Programming in Go - iakovlevorg
matically extracted from go source files and directly embedded in the PDF that To download and install Go, visit golang org/doc/install html which provides
[PDF] The Way to Go: A Thorough Introduction to the Go Programming
http://golang org/pkg shows documentation for the latest stable release; it us ( 22) Exporting code to different formats, such as pdf , html or even printing of the
[PDF] golang make
[PDF] gold first coursebook pdf
[PDF] gold pre first coursebook pdf
[PDF] gold's gym corporate discounts
[PDF] golden guide for class 9 maths free download pdf
[PDF] golf biarritz coronavirus
[PDF] good earplugs for drummers
[PDF] good restaurants in paris
[PDF] good restaurants in paris france
[PDF] good scientific figures
[PDF] google ads best practices
[PDF] google ads design
[PDF] google classroom class drive folder
[PDF] google cloud encryption in transit
The Go
Programming
Language
This page intentionally left blank
The Go Programming Language
Alan A. A. Donovan
Google Inc.
Brian W. Kernighan
Princeton University
New York € Boston € Indianapolis € San Francisco 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 trade- mark claim, the designations have been printed with initial capital letters or in all capitals. e authors and publisher have taken care in the preparation of this book, but make no expressedor 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.For information about buying this title in bulk quantities, or for special sales opportunities (which
may include electronic versions; custom cover designs; and content particular to your business, train-
ing goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419. For government sales inquiries, please contact governmentsales@pearsoned.com. For questions about sales outside the United States, please contact international@pearsoned.com.Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2015950709
Copyright © 2016 Alan A. A. Donovan & Brian W. KernighanAll rights reserved. Printed in the United States of America. is 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, 200 Old Tappan Road, Old Tappan, New Jersey 07675, or you may fax your request to (201) 236-3290. Front cover: Millau Viaduct, Tarn valley, southern France. A paragon of simplicity in modern engi-neering design, the viaduct replaced a convoluted path from capital to coast with a direct route over
the clouds. © Jean-Pierre Lescourret/Corbis. Back cover: the original Go gopher. © 2009 Renée French. Used under Creative Commons Attribu- tions 3.0 license. Typeset by the authors in Minion Pro, Lato, and Consolas, using Go, gro , ghostscript, and a host of other open-source Unix tools. Figures were created in Google Drawings.ISBN-13: 978-0-13-419044-0
ISBN-10: 0-13-419044-0
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.First printing, October 2015
Fo rLeil aan dMe gThe Go Programming Language
© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015This page intentionally left blank
Cont ents
Pr eface xi
TheOrigins ofGoxii
TheG oPro jec txiiiOrganizat ionofthe Bookxv
Wh ere toFindMoreInfor mat ionxvi
Ac knowledgments xvii
1. Tutorial1
1.1. Hel lo, Wor ld1
1.2. Command-L ineArguments 4
1.3. FindingDup lic ateLines 8
1.4. Animated GIFs 13
1.5. FetchingaURL 15
1.6. FetchingURLs Con cur rently17
1.7. AWe bServer 19
1.8. Loose End s23
2. Pro gramStr ucture27
2.1. Names 27
2.2. Declarat ions 28
2.3. Var iables 30
2.4. Assig nments 36
2.5. Typ eDecl arat ions 39
2.6. Packages andFiles 41
2.7. Scope 45
viiThe Go Programming Language© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015 viii CONTENTS3. Basic Data Typ es51
3.1. Int egers 51
3.2. Float ing-Point Numbers 56
3.3. Complex Numbers 61
3.4. Boole ans63
3.5. Str ings64
3.6. Con stants75
4. Com positeTyp es81
4.1. Arrays 81
4.2. Slices 84
4.3. Maps 93
4.4. Str ucts99
4.5. JSON107
4.6. Text andHTMLTempl ates113
5. Func tions 119
5.1. FunctionDeclarat ions 119
5.2. Rec ursion121
5.3. MultipleRetur nValues 124
5.4. Erro rs127
5.5. FunctionValues 132
5.6. Anony mou sFunc tions 135
5.7. Var iadic Functions 142
5.8. Defer red FunctionCal ls143
5.9. Panic 148
5.10. Recov er151
6. Metho ds155
6.1. Met hod Declarat ions 155
6.2. Met hodswit haPoint erReceiver158
6.3. ComposingTyp esby Str uct Emb edding161
6.4. Met hod Values andExpressions 164
6.5. Example: Bit Vec tor Typ e165
6.6. Encapsulat ion168
7. Interfaces171
7.1. Int erfaces as Contrac ts171
7.2. Int erface Typ es174
7.3. Int erface Satisfac tion175
7.4. ParsingFlags wit hflag.Value179
7.5. Int erface Values 181The Go Programming Language
© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015CONTENTSix
7.6. Sor tingwit hsort.Interface186
7.7. Thehttp.HandlerInterface 191
7.8. TheerrorInterface 196
7.9. Example: ExpressionEvaluator197
7.10. Typ eAs ser t
ions 2057.11. Discriminat ingError swith Typ eAs ser tions 206
7.12. Quer yingBeh avior swith Int erface Typ eAs ser tions 208
7.13. Typ eSw itch es210
7.14. Example: Token-B ased XML Decoding213
7.15. AFe wWo rds ofAdv ice 216
8. Gor o utines and Channels 217
8.1. Goroutines217
8.2. Example: Con cur rentClo ckSer ver 219
8.3. Example: Con cur rentEch oServer 222
8.4. Channel s225
8.5. Looping inParal lel234
8.6. Example: Con cur rentWeb Craw ler239
8.7. Multiplexingwit hselect244
8.8. Example: Con cur rentDirec tor yTraversal247
8.9. Cancellat ion251
8.10. Example: ChatSer ver 253
9. Concurrency withShared Vari ables257
9.1. Race Con dit ion s257
9.2. Mut ual Exc lusion:sync.Mutex262
9.3. Read/Write Mut exes:sync.RWMutex266
9.4. Memor ySy nchro nizat ion267
9.5. Lazy Initializat ion:sync.Once268
9.6. TheRace Detec tor 271
9.7. Example: Con cur rentNon-Blo cking Cache 272
9.8. Goroutinesand Threads 280
10. Pack agesand the GoTool283
10.1. Int roduc tion283
10.2. Imp ort Pat hs284
10.3. ThePackageDeclarat ion285
10.4. Imp ort Declarat ions 285
10.5. Blank Imp orts286
10.6. Packages andNaming289
10.7. TheGoTool290The Go Programming Language
© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015 xCONTENTS 11. T esting 30111.1. Thego testTo ol302
11.2.TestFunc tions 302
11.3. Cov erage318
11.4.BenchmarkFunc tions 321
11.5. ProØling323
11.6.ExampleFunc tions 326
12. Re
ecti on32912.1. Why Re‰ec tion?329
12.2.reflect.Typeandreflect.Value330
12.3.Display,aRec ursiveValue Print er333
12.4. Example: Enco dingS-E xpressions 338
12.5. Setting Var iables wit hreflect.Value341
12.6. Example: DecodingS-E xpressions 344
12.7. AccessingStr uct Field Tags 348
12.8. Displaying the Met hodsofaTyp e351
12.9. AWo rdofCaution 352
13. Low-L evel Pro gramming353
13.2.unsafe.Pointer356
13.3. Example: DeepEquivalence 358
13.4. Cal lingCCodewit hcgo361
13.5. Another WordofCaution 366
Index367The Go Programming Language
© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015Pref ace
22Go is anopensourc eprog rammi n glang uagethatmak esi
teasytobui ldsimpl e,rel iab le, an defxcientsof tware.¯¯(Fro mtheGoweb sit eatgolang.org) Go was conceive din Septemb er2007 byRob ert Gries emer,Rob Pike, and Ken Thomps on, all at Google, and was announced inNov emb er2009. Thegoals ofthe langu ageand its accom- pany ing tools weretobeexpressive, efØcientinbot hcomp ilation and exe cut ion,and effec tive in writing reliableand robustprograms. Go bears a sur facesimi lar ity toC and,likeC,isatoolfor prof essionalprogrammers, achie v- ingmaximum effe ctwit hminimum means.But it ismuchmorethananupdated versionof C. Itbor rowsand adaptsgood ide asfrom manyother langu ages, whi le avoidingfeaturesthat have led tocomplexity and unreliablecode. Its facilities for con cur rency are new and efØcient, andits approach to dat a abstrac tionand obj e ct-oriente dprog rammingisunu sually ‰exible. It hasaut omat icmemory managementorgarb age col lec tion. Go isesp eci ally wel lsuit edfor bui ldinginf rastr ucturelikenet wor ked ser vers, andtools and systems for prog rammers, but it istruly a general-pur pos elanguage andØnd sus ein domains as divers eas graphics, mobileapp lic ations,and machinelearning. Ithas becom epopu lar as a repl acementfor unt ypedscr ipt ing langu ages because itbal ances expressivenesswit hsafety : Go programstypic ally run fasterthanprogramswritt enindynamic langu ages andsuf fer far fe wer crashesdue tounexp ected typ eer ror s. Go isanopen-s ource pro jec t,sosourcecodefor itscompi ler,librar ies, andtools is fre ely avai l- able toany one.Contr ibution sto the pro jec tcome fro man active worldw ide community.Go runs onUnix-li kesystemsLinux, Fre eBSD, OpenBSD, Mac OS XandonPlan9and Micros oft Windows. Programswritt eninone ofthese env iro nmentsgeneral lywor kwithout mo diØcation on the others. xiThe Go Programming Language© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015 xii PREFACEThisbooki
smeant tohelpyou start usingGoeffec tive lyrig htaway andtouse itwel l,tak ing full advantage ofGoPslangu agefeaturesand stand ard librar iesto write clear, idiomatic, and efficientprograms.TheOrigins ofGo
Like biolog ical species, successf ullangu ages beget offspring thatincor poratethe advantagesof their ancestors;int erbre e dingsom etimesleads tosur prisingstrengt hs; and, ver yoccasionally, aradic alne wfe ature ariseswit houtpre cedent. Wecan lear nalot about why a langu ageisthe way itisand whatenv iro nment ithas beenadapt edfor bylooking atthese influences. The figurebelow shows the most imp ortantinfluences ofearlier programminglangu ages onthedesig nof Go.Go issom etimesdes crib edasa''C-li kelangu age,PPor as''Cfor the 21stcentury.PPFr omC,Go
in her ite ditsexpressionsyntax, cont rol-flow statements, basic dat atypes, cal l-by-value param- eter passing, point ers,and above all,CPsemp hasisonprogramsthatcompi letoefficientmachinecodeand cooperatenatural lywit htheabstrac tions ofcur rentoperat ingsystems.The Go Programming Language
© 2016 Alan A. A. Donovan & Brian W. Kernighan
revision 3b600c, date 29 Sep 2015THE ORIGINS OF GOxiii
Butthere are other an
cestors inGoPsfami lytre e.One maj orstreamofinfluence comesfro m languagesbyNik lausWir th, beg inningwit hPascal.Modula-2 inspired the packagecon cept. Ob ero neliminated the distinc tionbet weenmoduleint erface files andmoduleimp lementation fi les. Obero n-2 influence dthesyntaxfor packages, imports, anddeclarat ions,and Obj e ct Ob ero nprov ide dthesyntaxfor met hod declarat ions. Anot her lineage among GoPsancestors,and one thatmakes Godistinc tiveamong recent prog ramminglangu ages, isa sequence oflit tle-k now nresearch langu ages deve lop edatBel l Labs, allins pired bythe con ceptofcommu nicating sequent ial pro cesses(CSP) fro mTo ny Ho arePsseminal 1978 pap eron the found ation sof con cur rency.InCSP,aprogram isaparal lel comp osition of processesthathavenoshare dst ate;the pro cessescommunic ateand synchro- nize usingchannel s.But HoarePsCSP was a for mal langu agefor des cribingthe fundament al concepts ofcon cur rency,not a programminglangu agefor writing exe cut ableprograms. RobPikeand othersbegan toexp erimentwit hCSPimp lementation sas actu allangu ages. The fi rs twas cal le dSque ak (''Alangu agefor communic atingwit hmicePP), whichprovide dalan- gu agefor handlingmou seand key board events, wit hst aticallycre ate dch annel s.Thiswas fo llowe dby Newsque ak,whichoffered C-li kestatement and expressionsyntaxand Pas cal-li ke type not ation.Itwas a purelyfunctionallangu agewit hgarb agecol lec tion,again aimed at managing key board ,mous e,and windowevents. Channel sbecamefirs t-class values, dynami- callycre ate dandstorable in variables. ThePlan9operat ingsystemcar r iedthese ide asforwardinalangu agecal le dAlef.Alef tried to makeNewsque akaviablesystemprogramminglangu age, but itsomissionofgarb agecol- le ction made conc urrency too painf ul. Ot her cons tructions inGoshowthe influence ofnon-ancestral genes hereand there;for exampleiotais loosely fro mAPL, andlexic alscop ewith neste dfunc tions isfro mScheme (andmostlangu ages since). Heretoo we find nove lmu tat ions.GoPsinnovat ive slices provide dy namic arrays wit hefficientrandomaccessbut als opermit sop histicate dsh aring ar rangementsreminiscentoflin ked lists. And thedeferst atement isnew wit hGo.TheGoProject
Al lprog ramminglangu ages reflec ttheprogrammingphi losop hyoftheir creators,whichoften includes a significant component ofreactiontothe perceive dshortcomings ofearlier lan- gu ages. TheGopro jec twas bor neoffrust rat ionwit hseveral sof twaresystems atGooglethat were suf fer ingfro man explosionofcomplexity.(Thispro blem isbynomeans unique toGo ogle.)
As Rob Pikeput it,''comp lexity ismultiplic ativePP: fixingapro blem bymak ingone par tof the systemmorecomplex slowlybut surelyaddscomplexity toother par ts.Wi thcon stant pres- sure toadd featuresand opt ion sandconfigurat ions,and toshipcodequickly, itPseasy toneglec tsimplicity,eventhoug hin the lon grunsimplicity isthe key togood sof tware.The Go Programming Language