Previous Next

The Go Programming Language (Alan A. A. Donovan Brian W. Kernighan) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Alan A. A. Donovan & Brian W. Kernighan

GO

No Description

📄 File Format: PDF
💾 File Size: 4.8 MB
10
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
t.me/DevTwitter
📄 Page 2
The Go Programming Language t.me/DevTwitter
📄 Page 3
This page intentionally left blank t.me/DevTwitter
📄 Page 4
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 t.me/DevTwitter
📄 Page 5
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. Th 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. Th is publication is protected by copy- right, 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. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearsoned.com/permissions/. 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, groff , 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. Th ird printing, January 2016 t.me/DevTwitter
📄 Page 6
Fo r Leil a an d Me g The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 7
This page intentionally left blank t.me/DevTwitter
📄 Page 8
Cont ents Pr eface xi The Origins of Go xii The Go Pro jec t xiii Organizat ion of the Book xv Wh ere to Find More Infor mat ion xvi Ac knowledgments xvii 1. Tutorial 1 1.1. Hel lo, Wor ld 1 1.2. Command-L ine Arguments 4 1.3. Finding Dup lic ate Lines 8 1.4. Animated GIFs 13 1.5. Fetching a URL 15 1.6. Fetching URLs Con cur rently 17 1.7. A We b Server 19 1.8. Loose End s 23 2. Pro gram Str ucture 27 2.1. Names 27 2.2. Declarat ions 28 2.3. Var iables 30 2.4. Assig nments 36 2.5. Typ e Decl arat ions 39 2.6. Packages and Files 41 2.7. Scope 45 vii The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 9
viii  CONTENTS 3. Basic Data Typ es 51 3.1. Int egers 51 3.2. Float ing-Point Numbers 56 3.3. Complex Numbers 61 3.4. Boole ans 63 3.5. Str ings 64 3.6. Con stants 75 4. Com posite Typ es 81 4.1. Arrays 81 4.2. Slices 84 4.3. Maps 93 4.4. Str ucts 99 4.5. JSON 107 4.6. Text and HTML Templ ates 113 5. Func tions 119 5.1. Function Declarat ions 119 5.2. Rec ursion 121 5.3. Multiple Retur n Values 124 5.4. Erro rs 127 5.5. Function Values 132 5.6. Anony mou s Func tions 135 5.7. Var iadic Functions 142 5.8. Defer red Function Cal ls 143 5.9. Panic 148 5.10. Recov er 151 6. Metho ds 155 6.1. Met hod Declarat ions 155 6.2. Met hods wit h a Point er Receiver 158 6.3. Composing Typ es by Str uct Emb edding 161 6.4. Met hod Values and Expressions 164 6.5. Example: Bit Vec tor Typ e 165 6.6. Encapsulat ion 168 7. Interfaces 171 7.1. Int erfaces as Contrac ts 171 7.2. Int erface Typ es 174 7.3. Int erface Satisfac tion 175 7.4. Parsing Flags wit h flag.Value 179 7.5. Int erface Values 181 The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 10
CONTENTS ix 7.6. Sor ting wit h sort.Interface 186 7.7. The http.Handler Interface 191 7.8. The error Interface 196 7.9. Example: Expression Evaluator 197 7.10. Typ e As ser tions 205 7.11. Discriminat ing Error s with Typ e As ser tions 206 7.12. Quer ying Beh avior s with Int erface Typ e As ser tions 208 7.13. Typ e Sw itch es 210 7.14. Example: Token-B ased XML Decoding 213 7.15. A Fe w Wo rds of Adv ice 216 8. Gor o utines and Channels 217 8.1. Goroutines 217 8.2. Example: Con cur rent Clo ck Ser ver 219 8.3. Example: Con cur rent Ech o Server 222 8.4. Channel s 225 8.5. Looping in Paral lel 234 8.6. Example: Con cur rent Web Craw ler 239 8.7. Multiplexing wit h select 244 8.8. Example: Con cur rent Direc tor y Traversal 247 8.9. Cancellat ion 251 8.10. Example: Chat Ser ver 253 9. Concurrency with Shared Vari ables 257 9.1. Race Con dit ion s 257 9.2. Mut ual Exc lusion: sync.Mutex 262 9.3. Read/Write Mut exes: sync.RWMutex 266 9.4. Memor y Sy nchro nizat ion 267 9.5. Lazy Initializat ion: sync.Once 268 9.6. The Race Detec tor 271 9.7. Example: Con cur rent Non-Blo cking Cache 272 9.8. Goroutines and Threads 280 10. Pack ages and the Go Tool 283 10.1. Int roduc tion 283 10.2. Imp ort Pat hs 284 10.3. The Package Declarat ion 285 10.4. Imp ort Declarat ions 285 10.5. Blank Imp orts 286 10.6. Packages and Naming 289 10.7. The Go Tool 290 The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 11
x CONTENTS 11. Testing 301 11.1. The go test To ol 302 11.2. Test Func tions 302 11.3. Cov erage 318 11.4. Benchmark Func tions 321 11.5. Profiling 323 11.6. Example Func tions 326 12. Reflecti on 329 12.1. Why Reflec tion? 329 12.2. reflect.Type and reflect.Value 330 12.3. Display, a Rec ursive Value Print er 333 12.4. Example: Enco ding S-E xpressions 338 12.5. Setting Var iables wit h reflect.Value 341 12.6. Example: Decoding S-E xpressions 344 12.7. Accessing Str uct Field Tags 348 12.8. Displaying the Met hods of a Typ e 351 12.9. A Wo rd of Caution 352 13. Low-L evel Pro gramming 353 13.1. unsafe.Sizeof, Alignof, and Offsetof 354 13.2. unsafe.Pointer 356 13.3. Example: Deep Equivalence 358 13.4. Cal ling C Code wit h cgo 361 13.5. Another Word of Caution 366 Index 367 The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 12
Pref ace ‘‘Go is an open sourc e prog rammi n g lang uage that mak es it easy to bui ld simpl e, rel iab le, an d efficient sof tware.’’ (Fro m the Go web sit e at golang.org) Go was conceive d in Septemb er 2007 by Rob ert Gries emer, Rob Pike, and Ken Thomps on, all at Google, and was announced in Nov emb er 2009. The goals of the langu age and its accom- pany ing tools were to be expressive, efficient in bot h comp ilation and exe cut ion, and effec tive in writing reliable and robust programs. Go bears a sur face simi lar ity to C and, like C, is a tool for prof essional programmers, achie v- ing maximum effe ct wit h minimum means. But it is much more than an updated version of C. It bor rows and adapts good ide as from many other langu ages, whi le avoiding features that have led to complexity and unreliable code. Its facilities for con cur rency are new and efficient, and its approach to dat a abstrac tion and obj e ct-oriente d prog ramming is unu sually flexible. It has aut omat ic memory management or garb age col lec tion. Go is esp eci ally wel l suit ed for bui lding inf rastr ucture like net wor ked ser vers, and tools and systems for prog rammers, but it is truly a general-pur pos e language and find s us e in domains as divers e as graphics, mobile app lic ations, and machine learning. It has becom e popu lar as a repl acement for unt yped scr ipt ing langu ages because it bal ances expressiveness wit h safety : Go programs typic ally run faster than programs writt en in dynamic langu ages and suf fer far fe wer crashes due to unexp ected typ e er ror s. Go is an open-s ource pro jec t, so source code for its compi ler, librar ies, and tools is fre ely avai l- able to any one. Contr ibution s to the pro jec t come fro m an active worldw ide community. Go runs on Unix-li ke systems—Linux, Fre eBSD, OpenBSD, Mac OS X—and on Plan 9 and Micros oft Windows. Programs writt en in one of these env iro nments general ly wor k without mo dification on the others. xi The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 13
xii  PREFACE This book is meant to help you start using Go effec tive ly rig ht away and to use it wel l, tak ing full advantage of Go’s langu age features and stand ard librar ies to write clear, idiomatic, and efficient programs. The Origins of Go Like biolog ical species, successf ul langu ages beget offspring that incor porate the advantages of their ancestors; int erbre e ding som etimes leads to sur prising strengt hs; and, ver y occasionally, a radic al ne w fe ature arises wit hout pre cedent. We can lear n a lot about why a langu age is the way it is and what env iro nment it has been adapt ed for by looking at these influences. The figure below shows the most imp ortant influences of earlier programming langu ages on the desig n of Go. Go is som etimes des crib ed as a ‘‘C-li ke langu age,’’ or as ‘‘C for the 21st century.’’ Fr om C, Go in her ite d its expression syntax, cont rol-flow statements, basic dat a types, cal l-by-value param- eter passing, point ers, and above all, C’s emp hasis on programs that compi le to efficient machine code and cooperate natural ly wit h the abstrac tions of cur rent operat ing systems. The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 14
THE ORIGINS OF GO xiii But there are other ancestors in Go’s fami ly tre e. One maj or stream of influence comes fro m languages by Nik laus Wir th, beg inning wit h Pascal. Modula-2 inspired the package con cept. Ob ero n eliminated the distinc tion bet ween module int erface files and module imp lementation files. Obero n-2 influence d the syntax for packages, imports, and declarat ions, par tic ularly method declarat ions. Anot her lineage among Go’s ancestors, and one that makes Go distinc tive among recent prog ramming langu ages, is a sequence of lit tle-k now n research langu ages deve lop ed at Bel l Labs, all ins pired by the con cept of commu nicating sequent ial pro cesses (CSP) fro m To ny Ho are’s seminal 1978 pap er on the found ation s of con cur rency. In CSP, a program is a paral lel comp osition of processes that have no share d st ate; the pro cesses communic ate and synchro- nize using channel s. But Hoare’s CSP was a for mal langu age for des cribing the fundament al concepts of con cur rency, not a programming langu age for writing exe cut able programs. Rob Pike and others began to exp eriment wit h CSP imp lementation s as actu al langu ages. The firs t was cal le d Sque ak (‘‘A langu age for communic ating wit h mice’’), which provide d a lan- gu age for handling mou se and key board events, wit h st atically cre ate d ch annel s. This was fo llowe d by Newsque ak, which offered C-li ke statement and expression syntax and Pas cal-li ke type not ation. It was a purely functional langu age wit h garb age col lec tion, again aimed at managing key board , mous e, and window events. Channel s became firs t-class values, dynami- cally cre ate d and storable in variables. The Plan 9 operat ing system car r ied these ide as forward in a langu age cal le d Alef. Alef tried to make Newsque ak a viable system programming langu age, but its omission of garb age col- le ction made conc urrency too painf ul. Ot her cons tructions in Go show the influence of non-ancestral genes here and there; for example iota is loosely fro m APL, and lexic al scop e with neste d func tions is fro m Scheme (and most langu ages since). Here too we find nove l mu tat ions. Go’s innovat ive slices provide dy namic arrays wit h efficient random access but als o permit sop histicate d sh aring ar rangements reminiscent of lin ked lists. And the defer st atement is new wit h Go. The Go Project Al l prog ramming langu ages reflec t the programming phi losop hy of their creators, which often includes a significant component of reaction to the perceive d shortcomings of earlier lan- gu ages. The Go pro jec t was bor n of frust rat ion wit h several sof tware systems at Google that were suf fer ing fro m an explosion of complexity. (This pro blem is by no means unique to Go ogle.) As Rob Pike put it, ‘‘comp lexity is multiplic ative’’: fixing a pro blem by mak ing one par t of the system more complex slowly but surely adds complexity to other par ts. Wi th con stant pres- sure to add features and opt ion s and configurat ions, and to ship code quickly, it’s easy to neglec t simplicity, even thoug h in the lon g run simplicity is the key to good sof tware. t.me/DevTwitter
📄 Page 15
xiv  PREFACE Simp licity requires more wor k at the beg inning of a pro jec t to reduce an idea to its essence and more dis cip line over the lifet ime of a pro jec t to distinguish good changes fro m bad or per ni- cious ones. Wit h sufficient effor t, a good change can be accommodated wit hout compromis- ing what Fre d Brooks cal le d the ‘‘conceptu al int egr ity’’ of the desig n but a bad change cannot, and a per nicious change trades simplicity for its shallow cou sin, conv enience. Only through simplicity of desig n can a system remain stable, sec ure , and coh erent as it grows. The Go pro jec t includes the langu age its elf, its tools and stand ard librar ies, and last but not le ast, a cultural agenda of radic al simplicity. As a recent hig h-leve l language , Go has the bene- fit of hindsig ht, and the basics are don e we ll: it has garbage col lec tion, a package system, firs t- cl ass functions, lexic al scop e, a system cal l interface, and immut able str ings in which text is general ly encoded in UTF-8. But it has comp arat ive ly few features and is unlikely to add more . Fo r inst ance, it has no imp licit numer ic conv ersions, no con str uctor s or destr uctor s, no op erator overloading, no defau lt parameter values, no inher itance, no gener ics, no exception s, no macros, no function annot ation s, and no thread-lo cal storage. The langu age is mature and st able, and guarante es backwards compatibi lit y: older Go programs can be compi led and run with newer versions of compi lers and stand ard librar ies. Go has enough of a typ e system to avoid most of the careless mistakes that plague program- mers in dynamic langu ages, but it has a simpler typ e system than comparable typ ed langu ages. This appro ach can som etimes lead to isolate d pockets of ‘‘untyped’’ prog ramming wit hin a broader framewor k of typ es, and Go programmers do not go to the lengt hs that C++ or Haskel l prog rammers do to express safet y prop erties as typ e-bas ed pro ofs. But in prac tice Go gives programmers much of the safet y and run-t ime per for mance benefits of a rel ative ly st ron g type system wit hout the burden of a complex one. Go encourages an awareness of contemp orar y comp uter system desig n, partic ularly the importance of locality. Its bui lt-in dat a types and most librar y data str uctures are craf ted to work natural ly wit hout explicit initializat ion or imp licit con str uctor s, so rel ative ly few mem- or y al location s and memor y wr ites are hidden in the code. Go’s aggregate typ es (str ucts and ar rays) hold their elements direc tly, requir ing less storage and fewer allo cat ions and point er indirec tion s than langu ages that use indirec t fields. And since the moder n comp uter is a par- al lel machine, Go has conc urrency features bas ed on CSP, as mention ed earlier. The var iable- size stacks of Go’s lig htweig ht threads or goro utines are initial ly small enoug h that creating one goro utine is che ap and cre ating a million is prac tic al. Go’s stand ard librar y, often descr ibed as coming wit h ‘‘batt eries include d,’’ prov ides cle an building blo cks and APIs for I/O, text pro cessing, graphics, cryptography, net wor king, and dist ribut ed app lic ations, wit h supp ort for many stand ard file for mats and pro tocol s. The librar ies and tools make extensive use of convent ion to reduce the need for configurat ion and explanation, thu s simplif ying program logic and mak ing diverse Go programs more simi lar to each other and thu s easier to learn. Pro jec ts bui lt using the go to ol use only file and identifier names and an occ asional speci al comment to deter mine all the librar ies, exec utables, tests, benchmarks, examples, platfor m-specific var iants, and documentation for a proj e ct; the Go source its elf cont ains the bui ld sp ecification. The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 16
THE GO PROJECT xv Or ganization of the Book We assume that you have programmed in one or more other langu ages, whether comp ile d li ke C, C++, and Java, or int erprete d li ke Pyt hon, Ruby, and JavaS crip t, so we won’t spell out every- thing as if for a tot al beg inner. Sur face sy ntax will be fami liar, as will var iables and con stants, expressions, control flow, and functions. Chapter 1 is a tut orial on the basic cons tructs of Go, int roduce d thro ugh a dozen programs for ever yday tasks like reading and writing files, for matting text, creating images, and communi- cating wit h Internet clients and ser vers. Chapter 2 des crib es the str uctural elements of a Go program—de clarat ions, var iables, new types, packages and files, and scope. Chapt er 3 dis cusses numbers, boole ans, str ings, and con- st ants, and explains how to pro cess Unico de. Chapt er 4 des crib es composite typ es, that is, types bui lt up fro m simpler ones using arrays, maps, str ucts, and sli ces, Go’s appro ach to dy namic lists. Chapt er 5 cov ers functions and dis cusses error handling, panic and recover, and the defer st atement. Chapters 1 through 5 are thu s the basics, things that are par t of any mainst ream imp erat ive language . Go’s syntax and sty le som etimes dif fer fro m ot her langu ages, but most program- mers will pick them up quickly. The remaining chapt ers focus on topics where Go’s appro ach is less convent ion al: met hods, interfaces, conc urrency, packages, testing , and reflec tion. Go has an unusual appro ach to obj e ct-oriente d prog ramming. There are no class hierarchies, or indeed any class es; comp lex obj e ct beh avior s are cre ate d from simpler ones by composition, not inher itance. Met hods may be ass oci ated wit h any user-define d type, not just str uctures, and the rel ation ship bet ween con crete typ es and abstrac t types (interfaces) is imp licit, so a concrete typ e may sat isf y an interface that the typ e’s desig ner was unaware of. Met hods are covere d in Chapt er 6 and int erfaces in Chapt er 7. Chapter 8 presents Go’s appro ach to con cur rency, which is bas ed on the ide a of communic at- ing sequential pro cesses (CSP), embodie d by goroutines and channel s. Chapt er 9 explains the more tradition al asp ects of con cur rency bas ed on share d var iables. Chapter 10 des crib es packages, the mech anism for organizing librar ies. This chapt er als o shows how to make effec tive use of the go to ol, which provides for compi lat ion, testing , benchmarking , prog ram formatting , do cumentation, and many other tasks, all wit hin a single command. Chapter 11 deals wit h test ing , where Go takes a not ably lig htweig ht appro ach, avoiding abstrac tion-l aden framewor ks in favor of simple librar ies and tools. The testing librar ies prov ide a found ation atop which more complex abstrac tions can be bui lt if necessary. Chapter 12 dis cusses reflec tion, the abi lit y of a prog ram to examine its own represent ation during exe cut ion. Reflec tion is a pow erful tool, thoug h on e to be used caref ully; this chapt er explains finding the rig ht bal ance by showing how it is used to imp lement som e important Go librar ies. Chapter 13 explains the gor y det ails of low-le vel programming that uses the unsafe package to step aro und Go’s typ e system, and when that is appro priate. The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 17
xvi  PREFACE Each chapter has a number of exercis es that you can use to test your underst anding of Go, and to explore extensions and alt ernat ives to the examples fro m the book. Al l but the most trivial code examples in the book are avai lable for dow nlo ad from the public Git rep ository at gopl.io. Each example is identified by its package imp ort pat h and may be conv eniently fetch ed, bui lt, and ins tal le d using the go get command. You’ll need to cho ose a direc tor y to be your Go wor ksp ace and set the GOPATH enviro nment var iable to point to it. The go to ol will cre ate the direc tor y if necessary. For example: $ export GOPATH=$HOME/gobook # choose workspace directory $ go get gopl.io/ch1/helloworld # fetch, build, install $ $GOPATH/bin/helloworld  # run Hello, BF To run the examples, you will need at least version 1.5 of Go. $ go version go version go1.5 linux/amd64 Fo llow the ins tructions at https://golang.org/doc/install if the go to ol on your com- puter is older or missing. Where to Find More Information The best source for more infor mat ion about Go is the offici al we b site, https://golang.org, which provides access to the documentation, including the Go Programmi n g Lang uage Specifi- cati on, stand ard packages, and the like. There are als o tutorials on how to write Go and how to write it wel l, and a wide variet y of online text and vide o resources that will be valuable com- plements to this book. The Go Blog at blog.golang.org pu blishes som e of the best writing on Go, wit h ar ticles on the state of the langu age, plans for the fut ure , reports on conferences, and in-depth explanation s of a wide variet y of Go-rel ate d topics. One of the most useful asp ects of online access to Go (and a reg rettable limitation of a pap er book) is the abi lit y to run Go programs fro m the web pages that des crib e them. This func- tion ality is provide d by the Go Playg round at play.golang.org, and may be emb edde d within other pages, such as the home page at golang.org or the documentation pages ser ved by the godoc to ol. The Playg round makes it convenient to per for m simple exp eriments to che ck one’s under- st anding of syntax, semantics, or librar y packages wit h short programs, and in many ways takes the place of a re ad-e val-print loop (REPL) in other langu ages. Its persistent URLs are great for sharing snipp ets of Go code wit h ot hers, for rep orting bugs or mak ing sug gestion s. Built atop the Playg round, the Go Tour at tour.golang.org is a sequence of short int erac tive lessons on the basic ideas and con str uctions of Go, an orderly wal k thro ugh the langu age. The primary shortcoming of the Playg round and the Tour is that the y al low only stand ard librar ies to be imp orted, and many librar y fe atures—networ king, for example—are restr icted The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
📄 Page 18
WHERE TO FIND MORE INFORMATION  xvii for prac tic al or sec urity reasons. The y also require access to the Int ernet to compi le and run each program. So for more elaborate exp eriments, you will have to run Go programs on your ow n comp uter. For tunately the dow nlo ad process is straig htfor ward, so it should not take more than a few minut es to fetch the Go distr ibution fro m golang.org and start writing and running Go programs of your own. Since Go is an open-s ource pro jec t, you can read the code for any typ e or function in the stan- dard librar y on line at https://golang.org/pkg; the same code is par t of the dow nlo ade d dist ribut ion. Use this to figure out how som ething wor ks, or to answer question s ab out det ails, or merely to see how exp erts write really good Go. Acknowledgments Rob Pike and Russ Cox, core members of the Go team, read the manus cript several times wit h great care; their comments on everything fro m word choice to overal l st ruc ture and organiza- tion have been invaluable. Whi le prep aring the Jap anes e transl ation, Yoshi ki Shibata went far beyond the cal l of duty; his met iculou s eye spott ed numerou s inconsistencies in the Eng lish text and error s in the code. We gre atly appre ciate thoro ugh revie ws and critical comments on the ent ire manus cript fro m Br ian Goetz, Corey Kos ak, Ar nold Robbins, Josh Ble e cher Sny der, and Peter Weinberger. We are indebte d to Sameer Ajmani, Itt ai Bal aban, Dav id Crawshaw, Billy Don ahue, Jon athan Feinberg , Andrew Gerrand, Rob ert Gries emer, John Linder man, Minux Ma, Bryan Mills, Bal a Nataraj an, Cosmos Nicolaou , Paul Stanifor th, Nigel Tao, and Howard Trickey for many helpf ul sug gestion s. We als o than k David Brai lsford and Raph Levien for typ esetting adv ice, and Chr is Lop er for explaining many mysteries of e-b o ok pro duc tion. Our editor Greg Doench at Addison-Wesle y got the bal l ro lling originally and has been con- tinuou sly helpf ul ever since. The AW pro duc tion team—Jo hn Fuller, Day na Isley, Julie Nahi l, Chut i Pras ertsith, and Barb ara Wo o d—has been outst anding; author s could not hop e for bet- ter sup por t. Alan Don ovan wishes to thank: Sameer Ajmani, Chr is Demet riou, Walt Drummon d, and Reid Tatge at Google for allow ing him time to write; Steph en Don ovan, for his adv ice and timely encouragement; and above all, his wife Lei la Kazemi, for her unhesitating ent husi asm and unwaver ing sup por t for this pro jec t, despit e the lon g hours of distrac tion and abs ente eism from fami ly life that it ent ailed. Br ian Ker nighan is deeply gratef ul to friends and col leagues for their pat ience and forbearance as he mov ed slowly along the pat h to underst anding, and esp eci ally to his wife Meg , who has been unfailingly sup por tive of book-w rit ing and so much els e. Ne w Yo rk Oc tob er 2015 t.me/DevTwitter
📄 Page 19
This page intentionally left blank t.me/DevTwitter
📄 Page 20
1 Tutorial This chapt er is a tour of the basic comp onents of Go. We hop e to provide enough infor mat ion and examples to get you off the gro und and doing useful things as quickly as possible. The examples here, and indeed in the whole book, are aimed at tasks that you mig ht have to do in the real wor ld. In this chapt er we’ll try to give you a taste of the diversity of programs that one mig ht write in Go, ranging fro m simple file pro cessing and a bit of graphics to con cur rent Internet clients and ser vers. We cer tain ly won’t explain everything in the firs t ch apt er, but studying such programs in a new langu age can be an effec tive way to get started. Wh en you’re learning a new langu age, there’s a natural tendency to write code as you wou ld have writt en it in a langu age you already know. Be aware of this bias as you learn Go and try to avoid it. We’ve tried to illustrate and explain how to write good Go, so use the code here as a guide when you’re writing your own. 1.1.  Hello, World We’ll start wit h the now-t radition al ‘‘hel lo, wor ld’’ example, which app ears at the beg inning of The C Programmi n g Lang uage, publishe d in 1978. C is one of the most direc t influences on Go, and ‘‘hel lo, wor ld’’ illustrates a number of central ideas. gopl.io/ch1/helloworld package main import "fmt" func main() { fmt.Println("Hello, BF") } 1 The Go Programming Language © 2016 Alan A. A. Donovan & Brian W. Kernighan revision 3b600c, date 29 Sep 2015 t.me/DevTwitter
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List