[PDF] [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-



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 interfaces best practices

[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 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.

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. Kernighan

All 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 2015

This page intentionally left blank

Cont ents

Pr eface xi

TheOrigins ofGoxii

TheG oPro jec txiii

Organizat 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 CONTENTS

3. 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 2015

CONTENTSix

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 205

7.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 301

11.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 on329

12.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 2015

Pref 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 kesystemsŠLinux, Fre eBSD, OpenBSD, Mac OS XŠandonPlan9and 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 PREFACE

Thisbooki

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 on

thedesig 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 letoefficient

machinecodeand cooperatenatural lywit htheabstrac tions ofcur rentoperat ingsystems.The Go Programming Language

© 2016 Alan A. A. Donovan & Brian W. Kernighan

revision 3b600c, date 29 Sep 2015

THE 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 to

Go 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 to

neglec tsimplicity,eventhoug hin the lon grunsimplicity isthe key togood sof tware.The Go Programming Language

© 2016 Alan A. A. Donovan & Brian W. Kernighan

revision 3b600c, date 29 Sep 2015 xiv PREFACE Simp licity requires morewor kat the beg inningofapro jec tto reduce an ideat oits essenceand more dis cip lineoverthe lifet imeofapro jec tto distinguish good changesfro mbadorper ni- cious ones. Wit hsufficienteffor t,agood change can beaccommodated wit houtcompromis- ingwhatFre dBrooks cal le dthe''conceptu alint egr ityPPof the desig nbutabad change cannot, andaper nicious change trades simplicity for itsshallow cou sin, conv enience.Onlythrough simplicity ofdesig ncanasystemremain stable, sec ure ,andcoh erent asitgrows. TheGopro jec tincludes the langu ageits elf,its tools and stand ard librar ies, andlastbut not le ast, a cultural agenda ofradic al simplicity.Asarecenthig h-leve llanguage ,Go has the bene- fi tofhindsig ht, andthe basics aredon ewe ll: ithas garbagecol lec tion,apackagesystem, firs t- cl ass functions,lexic alscop e,asystemcal l interface,and immut ablestr ingsinwhichtext is general lyencoded inUTF-8. But it has comp arat ive lyfew featuresand isunlikelytoadd more .Fo rinst ance, ithas noimp licitnumer ic conv ersions,nocon str uctor sor destr uctor s,no op erator overloading, nodefau ltparameter values, noinher itance, nogener ics,no exception s, no macros, nofunctionannot ation s,and no thread-lo cal storage. The langu ageismatureand st able, and guarante esbackwards compatibi lit y:older Goprogramscan becompi led and run with newer versions ofcompi lersand stand ard librar ies. Go has enough ofatyp e systemtoavoid mostofthe carelessmistakesthatplague program- mers indynamic langu ages, but it has a simpler typ e systemthancomparable typ edlangu ages. Thisappro ach can som etimesleadtoisolate dpockets of''untypedPPprog rammingwit hin a broader framewor kof typ es, andGoprogrammersdonot gotothe lengt hsthatC++ or Haskel lprog rammersdotoexpress safet yprop erties as typ e-bas edpro ofs. But inprac tice Go givesprogrammersmuchofthe safet y andrun-t imeper for mance benefits ofarel ative ly st ron gtype systemwit houtthe burden ofacomplex one. Go encourages an awarenessofcontemp orar y comp utersystemdesig n,partic ularlythe importance oflocality.Its bui lt-in dat atypesand most librar ydata str uctures arecraf ted to work natural lywit houtexplicitinitializat ionorimp licitcon str uctor s,sorel ative lyfew mem- or yal location sandmemor ywr itesare hidden in the code. GoPsaggregatetyp es (str uctsand ar rays)hold their elements direc tly,requir inglessstorageand fewer allo cat ions and point er indirec tion sthan langu ages thatuse indirec tfields.And since the moder n comp uterisapar- al lelmachine, Gohas conc urrency featuresbas edonCSP,asmention edearlier.The var iable- size stacksofGoPslig htweig htthreads orgoro utinesareinitial lysmall enoug hthat creating one goro utine ische apand cre ating a millionisprac tic al. GoPsstand ard librar y,often descr ibedascomingwit h''batt eries include d,PPprov ides cle an buildingblo cks andAPIsfor I/O,text pro cessing, graphics, cryptography,net wor king, and dist ribut edapp lic ations,wit hsupp ort for manystand ardfile for mats andpro tocol s.The librar ies andtools make extensive use ofconvent ion toreduce the need for configurat ionand explanation,thu ssimplif yingprogram logic andmak ingdiverse Go programsmoresimi lar to each other andthu seasier tolearn.Pro jec tsbui ltusingthegoto oluse only file andidentifier namesand anocc asionalspeci al commenttodeter mineall the librar ies, exec utables, tests, benchmarks, examples, platfor m-specificvar iants, anddocumentation for a proj e ct; the Go source its elf cont ainsthe bui ldsp ecification.The Go Programming Language

© 2016 Alan A. A. Donovan & Brian W. Kernighan

revision 3b600c, date 29 Sep 2015

THE GO PROJECTxv

Or ganization ofthe B

ook We assume thatyou haveprogrammed inone ormoreother langu ages, whether comp ile d li ke C, C++, andJava, orint erprete dli kePyt hon,Ruby, and JavaS crip t,sowewonPtspell out every- thingasiffor a tot albeg inner.Sur facesy ntaxwill befami liar,aswill var iables andcon stants, expressions,control‰ow,and functions. Chapter1 isatut orialonthe basic cons tructsofGo, int roduce dthro ugh a dozen programsfor ever ydaytasks like readingand writingØles, for matting text, creating images, andcommuni- cating wit hInternet clients andser vers. Chapter2 des crib esthe str uctural elements ofaGoprogramŠde clarat ions,var iables, new types, packages and Øles, andscope.Chapt er3 dis cussesnumbers,boole ans, str ings, andcon- st ants, andexplainshow topro cessUnico de.Chapt er4 des crib escomposite typ es,that is, typesbui ltupfro msimpler onesusingarrays, maps, str ucts, andsli ces,GoPsappro ach to dy namic lists. Chapt er5 cov ers functions and dis cusseserror handling,panicandrecover, andthedeferst atement. Chapters 1 through 5 are thu sthebasics, things thatare par tof any mainst reamimp erat ive language .GoPssyntaxand sty lesom etimesdif fer fro mot her langu ages, but mostprogram- mers will pickthemupquickly. The remainingchapt ers focus ontopics where GoPsappro ach is lessconvent ion al: met hods, interfaces, conc urrency,packages, testing ,andre‰ec tion. Go has an unusualappro ach to obj e ct-oriente dprog ramming. There are noclass hierarchies, or indeed any class es; comp lex obj e ctbeh avior sarecre ate dfrom simpler onesbycomposition, notinher itance. Met hodsmay beass oci ated wit hanyuser-deØne dtype,not juststr uctures, andthe rel ation shipbet weencon crete typ es andabstrac ttypes(interfaces)isimp licit, soa concrete typ emaysat isf yan interface thatthe typ ePsdesig ner was unawareof. Met hodsare covere din Chapt er6and int erfaces in Chapt er7. Chapter8 presentsGoPsappro ach to con cur rency,whichisbas edonthe ide aof communic at- ingsequential pro cesses(CSP), embodie dby goroutinesand channel s.Chapt er9 explainsthe more tradition alasp ectsofcon cur rency bas edonshare dvar iables. Chapter10des crib espackages, the mech anism for organizinglibrar ies. Thischapt erals o shows how tomakeeffec tive use ofthegoto ol, whichprovides for compi lat ion, testing , benchmarking ,prog ramformatting ,do cumentation,and manyother tasks, allwit hin a single command. Chapter11deals wit htest ing ,whereGotakes a not ably lig htweig htappro ach,avoiding abstrac tion-l adenframewor ksinfavor of simplelibrar ies andtools.The testing librar ies prov ide a found ation atopwhichmorecomplex abstrac tions can bebui ltifnecessary. Chapter12dis cussesre‰ec tion,the abi lit yof a prog ramto examineits own represent ation during exe cut ion.Re‰ec tion isapow erfultool, thoug hon eto beusedcaref ully; thischapt er explains Øndingthe rig htbal ance byshowing how itisusedtoimp lementsom eimportantGo librar ies.Chapter13explainsthe gor ydet ails oflow-le vel programmingthatusestheunsafe packagetosteparo und GoPstyp e system, andwhenthatisappro priate.The Go Programming Language

© 2016 Alan A. A. Donovan & Brian W. Kernighan

revision 3b600c, date 29 Sep 2015 xvi PREFACE

Each chapterhas a n

umberofexercis esthatyou can use totestyourunderst andingofGo, and to explore extensions and alt ernat ivestothe examples fro mthebook. Al lbutthe most trivialcodeexamples in the bookare avai lable for dow nlo adfrom the publicquotesdbs_dbs17.pdfusesText_23