effective_go.html 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666
  1. <!--{
  2. "Title": "Effective Go",
  3. "Template": true
  4. }-->
  5. <h2 id="introduction">Introduction</h2>
  6. <p>
  7. Go is a new language. Although it borrows ideas from
  8. existing languages,
  9. it has unusual properties that make effective Go programs
  10. different in character from programs written in its relatives.
  11. A straightforward translation of a C++ or Java program into Go
  12. is unlikely to produce a satisfactory result&mdash;Java programs
  13. are written in Java, not Go.
  14. On the other hand, thinking about the problem from a Go
  15. perspective could produce a successful but quite different
  16. program.
  17. In other words,
  18. to write Go well, it's important to understand its properties
  19. and idioms.
  20. It's also important to know the established conventions for
  21. programming in Go, such as naming, formatting, program
  22. construction, and so on, so that programs you write
  23. will be easy for other Go programmers to understand.
  24. </p>
  25. <p>
  26. This document gives tips for writing clear, idiomatic Go code.
  27. It augments the <a href="/ref/spec">language specification</a>,
  28. the <a href="//tour.golang.org/">Tour of Go</a>,
  29. and <a href="/doc/code.html">How to Write Go Code</a>,
  30. all of which you
  31. should read first.
  32. </p>
  33. <h3 id="examples">Examples</h3>
  34. <p>
  35. The <a href="/src/">Go package sources</a>
  36. are intended to serve not
  37. only as the core library but also as examples of how to
  38. use the language.
  39. Moreover, many of the packages contain working, self-contained
  40. executable examples you can run directly from the
  41. <a href="//golang.org">golang.org</a> web site, such as
  42. <a href="//golang.org/pkg/strings/#example_Map">this one</a> (if
  43. necessary, click on the word "Example" to open it up).
  44. If you have a question about how to approach a problem or how something
  45. might be implemented, the documentation, code and examples in the
  46. library can provide answers, ideas and
  47. background.
  48. </p>
  49. <h2 id="formatting">Formatting</h2>
  50. <p>
  51. Formatting issues are the most contentious
  52. but the least consequential.
  53. People can adapt to different formatting styles
  54. but it's better if they don't have to, and
  55. less time is devoted to the topic
  56. if everyone adheres to the same style.
  57. The problem is how to approach this Utopia without a long
  58. prescriptive style guide.
  59. </p>
  60. <p>
  61. With Go we take an unusual
  62. approach and let the machine
  63. take care of most formatting issues.
  64. The <code>gofmt</code> program
  65. (also available as <code>go fmt</code>, which
  66. operates at the package level rather than source file level)
  67. reads a Go program
  68. and emits the source in a standard style of indentation
  69. and vertical alignment, retaining and if necessary
  70. reformatting comments.
  71. If you want to know how to handle some new layout
  72. situation, run <code>gofmt</code>; if the answer doesn't
  73. seem right, rearrange your program (or file a bug about <code>gofmt</code>),
  74. don't work around it.
  75. </p>
  76. <p>
  77. As an example, there's no need to spend time lining up
  78. the comments on the fields of a structure.
  79. <code>Gofmt</code> will do that for you. Given the
  80. declaration
  81. </p>
  82. <pre>
  83. type T struct {
  84. name string // name of the object
  85. value int // its value
  86. }
  87. </pre>
  88. <p>
  89. <code>gofmt</code> will line up the columns:
  90. </p>
  91. <pre>
  92. type T struct {
  93. name string // name of the object
  94. value int // its value
  95. }
  96. </pre>
  97. <p>
  98. All Go code in the standard packages has been formatted with <code>gofmt</code>.
  99. </p>
  100. <p>
  101. Some formatting details remain. Very briefly:
  102. </p>
  103. <dl>
  104. <dt>Indentation</dt>
  105. <dd>We use tabs for indentation and <code>gofmt</code> emits them by default.
  106. Use spaces only if you must.
  107. </dd>
  108. <dt>Line length</dt>
  109. <dd>
  110. Go has no line length limit. Don't worry about overflowing a punched card.
  111. If a line feels too long, wrap it and indent with an extra tab.
  112. </dd>
  113. <dt>Parentheses</dt>
  114. <dd>
  115. Go needs fewer parentheses than C and Java: control structures (<code>if</code>,
  116. <code>for</code>, <code>switch</code>) do not have parentheses in
  117. their syntax.
  118. Also, the operator precedence hierarchy is shorter and clearer, so
  119. <pre>
  120. x&lt;&lt;8 + y&lt;&lt;16
  121. </pre>
  122. means what the spacing implies, unlike in the other languages.
  123. </dd>
  124. </dl>
  125. <h2 id="commentary">Commentary</h2>
  126. <p>
  127. Go provides C-style <code>/* */</code> block comments
  128. and C++-style <code>//</code> line comments.
  129. Line comments are the norm;
  130. block comments appear mostly as package comments, but
  131. are useful within an expression or to disable large swaths of code.
  132. </p>
  133. <p>
  134. The program—and web server—<code>godoc</code> processes
  135. Go source files to extract documentation about the contents of the
  136. package.
  137. Comments that appear before top-level declarations, with no intervening newlines,
  138. are extracted along with the declaration to serve as explanatory text for the item.
  139. The nature and style of these comments determines the
  140. quality of the documentation <code>godoc</code> produces.
  141. </p>
  142. <p>
  143. Every package should have a <i>package comment</i>, a block
  144. comment preceding the package clause.
  145. For multi-file packages, the package comment only needs to be
  146. present in one file, and any one will do.
  147. The package comment should introduce the package and
  148. provide information relevant to the package as a whole.
  149. It will appear first on the <code>godoc</code> page and
  150. should set up the detailed documentation that follows.
  151. </p>
  152. <pre>
  153. /*
  154. Package regexp implements a simple library for regular expressions.
  155. The syntax of the regular expressions accepted is:
  156. regexp:
  157. concatenation { '|' concatenation }
  158. concatenation:
  159. { closure }
  160. closure:
  161. term [ '*' | '+' | '?' ]
  162. term:
  163. '^'
  164. '$'
  165. '.'
  166. character
  167. '[' [ '^' ] character-ranges ']'
  168. '(' regexp ')'
  169. */
  170. package regexp
  171. </pre>
  172. <p>
  173. If the package is simple, the package comment can be brief.
  174. </p>
  175. <pre>
  176. // Package path implements utility routines for
  177. // manipulating slash-separated filename paths.
  178. </pre>
  179. <p>
  180. Comments do not need extra formatting such as banners of stars.
  181. The generated output may not even be presented in a fixed-width font, so don't depend
  182. on spacing for alignment&mdash;<code>godoc</code>, like <code>gofmt</code>,
  183. takes care of that.
  184. The comments are uninterpreted plain text, so HTML and other
  185. annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should
  186. not be used.
  187. One adjustment <code>godoc</code> does do is to display indented
  188. text in a fixed-width font, suitable for program snippets.
  189. The package comment for the
  190. <a href="/pkg/fmt/"><code>fmt</code> package</a> uses this to good effect.
  191. </p>
  192. <p>
  193. Depending on the context, <code>godoc</code> might not even
  194. reformat comments, so make sure they look good straight up:
  195. use correct spelling, punctuation, and sentence structure,
  196. fold long lines, and so on.
  197. </p>
  198. <p>
  199. Inside a package, any comment immediately preceding a top-level declaration
  200. serves as a <i>doc comment</i> for that declaration.
  201. Every exported (capitalized) name in a program should
  202. have a doc comment.
  203. </p>
  204. <p>
  205. Doc comments work best as complete sentences, which allow
  206. a wide variety of automated presentations.
  207. The first sentence should be a one-sentence summary that
  208. starts with the name being declared.
  209. </p>
  210. <pre>
  211. // Compile parses a regular expression and returns, if successful,
  212. // a Regexp that can be used to match against text.
  213. func Compile(str string) (*Regexp, error) {
  214. </pre>
  215. <p>
  216. If every doc comment begins with the name of the item it describes,
  217. the output of <code>godoc</code> can usefully be run through <code>grep</code>.
  218. Imagine you couldn't remember the name "Compile" but were looking for
  219. the parsing function for regular expressions, so you ran
  220. the command,
  221. </p>
  222. <pre>
  223. $ godoc regexp | grep -i parse
  224. </pre>
  225. <p>
  226. If all the doc comments in the package began, "This function...", <code>grep</code>
  227. wouldn't help you remember the name. But because the package starts each
  228. doc comment with the name, you'd see something like this,
  229. which recalls the word you're looking for.
  230. </p>
  231. <pre>
  232. $ godoc regexp | grep parse
  233. Compile parses a regular expression and returns, if successful, a Regexp
  234. parsed. It simplifies safe initialization of global variables holding
  235. cannot be parsed. It simplifies safe initialization of global variables
  236. $
  237. </pre>
  238. <p>
  239. Go's declaration syntax allows grouping of declarations.
  240. A single doc comment can introduce a group of related constants or variables.
  241. Since the whole declaration is presented, such a comment can often be perfunctory.
  242. </p>
  243. <pre>
  244. // Error codes returned by failures to parse an expression.
  245. var (
  246. ErrInternal = errors.New("regexp: internal error")
  247. ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
  248. ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
  249. ...
  250. )
  251. </pre>
  252. <p>
  253. Grouping can also indicate relationships between items,
  254. such as the fact that a set of variables is protected by a mutex.
  255. </p>
  256. <pre>
  257. var (
  258. countLock sync.Mutex
  259. inputCount uint32
  260. outputCount uint32
  261. errorCount uint32
  262. )
  263. </pre>
  264. <h2 id="names">Names</h2>
  265. <p>
  266. Names are as important in Go as in any other language.
  267. They even have semantic effect:
  268. the visibility of a name outside a package is determined by whether its
  269. first character is upper case.
  270. It's therefore worth spending a little time talking about naming conventions
  271. in Go programs.
  272. </p>
  273. <h3 id="package-names">Package names</h3>
  274. <p>
  275. When a package is imported, the package name becomes an accessor for the
  276. contents. After
  277. </p>
  278. <pre>
  279. import "bytes"
  280. </pre>
  281. <p>
  282. the importing package can talk about <code>bytes.Buffer</code>. It's
  283. helpful if everyone using the package can use the same name to refer to
  284. its contents, which implies that the package name should be good:
  285. short, concise, evocative. By convention, packages are given
  286. lower case, single-word names; there should be no need for underscores
  287. or mixedCaps.
  288. Err on the side of brevity, since everyone using your
  289. package will be typing that name.
  290. And don't worry about collisions <i>a priori</i>.
  291. The package name is only the default name for imports; it need not be unique
  292. across all source code, and in the rare case of a collision the
  293. importing package can choose a different name to use locally.
  294. In any case, confusion is rare because the file name in the import
  295. determines just which package is being used.
  296. </p>
  297. <p>
  298. Another convention is that the package name is the base name of
  299. its source directory;
  300. the package in <code>src/encoding/base64</code>
  301. is imported as <code>"encoding/base64"</code> but has name <code>base64</code>,
  302. not <code>encoding_base64</code> and not <code>encodingBase64</code>.
  303. </p>
  304. <p>
  305. The importer of a package will use the name to refer to its contents,
  306. so exported names in the package can use that fact
  307. to avoid stutter.
  308. (Don't use the <code>import .</code> notation, which can simplify
  309. tests that must run outside the package they are testing, but should otherwise be avoided.)
  310. For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>,
  311. not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>,
  312. which is a clear, concise name.
  313. Moreover,
  314. because imported entities are always addressed with their package name, <code>bufio.Reader</code>
  315. does not conflict with <code>io.Reader</code>.
  316. Similarly, the function to make new instances of <code>ring.Ring</code>&mdash;which
  317. is the definition of a <em>constructor</em> in Go&mdash;would
  318. normally be called <code>NewRing</code>, but since
  319. <code>Ring</code> is the only type exported by the package, and since the
  320. package is called <code>ring</code>, it's called just <code>New</code>,
  321. which clients of the package see as <code>ring.New</code>.
  322. Use the package structure to help you choose good names.
  323. </p>
  324. <p>
  325. Another short example is <code>once.Do</code>;
  326. <code>once.Do(setup)</code> reads well and would not be improved by
  327. writing <code>once.DoOrWaitUntilDone(setup)</code>.
  328. Long names don't automatically make things more readable.
  329. A helpful doc comment can often be more valuable than an extra long name.
  330. </p>
  331. <h3 id="Getters">Getters</h3>
  332. <p>
  333. Go doesn't provide automatic support for getters and setters.
  334. There's nothing wrong with providing getters and setters yourself,
  335. and it's often appropriate to do so, but it's neither idiomatic nor necessary
  336. to put <code>Get</code> into the getter's name. If you have a field called
  337. <code>owner</code> (lower case, unexported), the getter method should be
  338. called <code>Owner</code> (upper case, exported), not <code>GetOwner</code>.
  339. The use of upper-case names for export provides the hook to discriminate
  340. the field from the method.
  341. A setter function, if needed, will likely be called <code>SetOwner</code>.
  342. Both names read well in practice:
  343. </p>
  344. <pre>
  345. owner := obj.Owner()
  346. if owner != user {
  347. obj.SetOwner(user)
  348. }
  349. </pre>
  350. <h3 id="interface-names">Interface names</h3>
  351. <p>
  352. By convention, one-method interfaces are named by
  353. the method name plus an -er suffix or similar modification
  354. to construct an agent noun: <code>Reader</code>,
  355. <code>Writer</code>, <code>Formatter</code>,
  356. <code>CloseNotifier</code> etc.
  357. </p>
  358. <p>
  359. There are a number of such names and it's productive to honor them and the function
  360. names they capture.
  361. <code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>,
  362. <code>String</code> and so on have
  363. canonical signatures and meanings. To avoid confusion,
  364. don't give your method one of those names unless it
  365. has the same signature and meaning.
  366. Conversely, if your type implements a method with the
  367. same meaning as a method on a well-known type,
  368. give it the same name and signature;
  369. call your string-converter method <code>String</code> not <code>ToString</code>.
  370. </p>
  371. <h3 id="mixed-caps">MixedCaps</h3>
  372. <p>
  373. Finally, the convention in Go is to use <code>MixedCaps</code>
  374. or <code>mixedCaps</code> rather than underscores to write
  375. multiword names.
  376. </p>
  377. <h2 id="semicolons">Semicolons</h2>
  378. <p>
  379. Like C, Go's formal grammar uses semicolons to terminate statements,
  380. but unlike in C, those semicolons do not appear in the source.
  381. Instead the lexer uses a simple rule to insert semicolons automatically
  382. as it scans, so the input text is mostly free of them.
  383. </p>
  384. <p>
  385. The rule is this. If the last token before a newline is an identifier
  386. (which includes words like <code>int</code> and <code>float64</code>),
  387. a basic literal such as a number or string constant, or one of the
  388. tokens
  389. </p>
  390. <pre>
  391. break continue fallthrough return ++ -- ) }
  392. </pre>
  393. <p>
  394. the lexer always inserts a semicolon after the token.
  395. This could be summarized as, &ldquo;if the newline comes
  396. after a token that could end a statement, insert a semicolon&rdquo;.
  397. </p>
  398. <p>
  399. A semicolon can also be omitted immediately before a closing brace,
  400. so a statement such as
  401. </p>
  402. <pre>
  403. go func() { for { dst &lt;- &lt;-src } }()
  404. </pre>
  405. <p>
  406. needs no semicolons.
  407. Idiomatic Go programs have semicolons only in places such as
  408. <code>for</code> loop clauses, to separate the initializer, condition, and
  409. continuation elements. They are also necessary to separate multiple
  410. statements on a line, should you write code that way.
  411. </p>
  412. <p>
  413. One consequence of the semicolon insertion rules
  414. is that you cannot put the opening brace of a
  415. control structure (<code>if</code>, <code>for</code>, <code>switch</code>,
  416. or <code>select</code>) on the next line. If you do, a semicolon
  417. will be inserted before the brace, which could cause unwanted
  418. effects. Write them like this
  419. </p>
  420. <pre>
  421. if i &lt; f() {
  422. g()
  423. }
  424. </pre>
  425. <p>
  426. not like this
  427. </p>
  428. <pre>
  429. if i &lt; f() // wrong!
  430. { // wrong!
  431. g()
  432. }
  433. </pre>
  434. <h2 id="control-structures">Control structures</h2>
  435. <p>
  436. The control structures of Go are related to those of C but differ
  437. in important ways.
  438. There is no <code>do</code> or <code>while</code> loop, only a
  439. slightly generalized
  440. <code>for</code>;
  441. <code>switch</code> is more flexible;
  442. <code>if</code> and <code>switch</code> accept an optional
  443. initialization statement like that of <code>for</code>;
  444. <code>break</code> and <code>continue</code> statements
  445. take an optional label to identify what to break or continue;
  446. and there are new control structures including a type switch and a
  447. multiway communications multiplexer, <code>select</code>.
  448. The syntax is also slightly different:
  449. there are no parentheses
  450. and the bodies must always be brace-delimited.
  451. </p>
  452. <h3 id="if">If</h3>
  453. <p>
  454. In Go a simple <code>if</code> looks like this:
  455. </p>
  456. <pre>
  457. if x &gt; 0 {
  458. return y
  459. }
  460. </pre>
  461. <p>
  462. Mandatory braces encourage writing simple <code>if</code> statements
  463. on multiple lines. It's good style to do so anyway,
  464. especially when the body contains a control statement such as a
  465. <code>return</code> or <code>break</code>.
  466. </p>
  467. <p>
  468. Since <code>if</code> and <code>switch</code> accept an initialization
  469. statement, it's common to see one used to set up a local variable.
  470. </p>
  471. <pre>
  472. if err := file.Chmod(0664); err != nil {
  473. log.Print(err)
  474. return err
  475. }
  476. </pre>
  477. <p id="else">
  478. In the Go libraries, you'll find that
  479. when an <code>if</code> statement doesn't flow into the next statement—that is,
  480. the body ends in <code>break</code>, <code>continue</code>,
  481. <code>goto</code>, or <code>return</code>—the unnecessary
  482. <code>else</code> is omitted.
  483. </p>
  484. <pre>
  485. f, err := os.Open(name)
  486. if err != nil {
  487. return err
  488. }
  489. codeUsing(f)
  490. </pre>
  491. <p>
  492. This is an example of a common situation where code must guard against a
  493. sequence of error conditions. The code reads well if the
  494. successful flow of control runs down the page, eliminating error cases
  495. as they arise. Since error cases tend to end in <code>return</code>
  496. statements, the resulting code needs no <code>else</code> statements.
  497. </p>
  498. <pre>
  499. f, err := os.Open(name)
  500. if err != nil {
  501. return err
  502. }
  503. d, err := f.Stat()
  504. if err != nil {
  505. f.Close()
  506. return err
  507. }
  508. codeUsing(f, d)
  509. </pre>
  510. <h3 id="redeclaration">Redeclaration and reassignment</h3>
  511. <p>
  512. An aside: The last example in the previous section demonstrates a detail of how the
  513. <code>:=</code> short declaration form works.
  514. The declaration that calls <code>os.Open</code> reads,
  515. </p>
  516. <pre>
  517. f, err := os.Open(name)
  518. </pre>
  519. <p>
  520. This statement declares two variables, <code>f</code> and <code>err</code>.
  521. A few lines later, the call to <code>f.Stat</code> reads,
  522. </p>
  523. <pre>
  524. d, err := f.Stat()
  525. </pre>
  526. <p>
  527. which looks as if it declares <code>d</code> and <code>err</code>.
  528. Notice, though, that <code>err</code> appears in both statements.
  529. This duplication is legal: <code>err</code> is declared by the first statement,
  530. but only <em>re-assigned</em> in the second.
  531. This means that the call to <code>f.Stat</code> uses the existing
  532. <code>err</code> variable declared above, and just gives it a new value.
  533. </p>
  534. <p>
  535. In a <code>:=</code> declaration a variable <code>v</code> may appear even
  536. if it has already been declared, provided:
  537. </p>
  538. <ul>
  539. <li>this declaration is in the same scope as the existing declaration of <code>v</code>
  540. (if <code>v</code> is already declared in an outer scope, the declaration will create a new variable §),</li>
  541. <li>the corresponding value in the initialization is assignable to <code>v</code>, and</li>
  542. <li>there is at least one other variable in the declaration that is being declared anew.</li>
  543. </ul>
  544. <p>
  545. This unusual property is pure pragmatism,
  546. making it easy to use a single <code>err</code> value, for example,
  547. in a long <code>if-else</code> chain.
  548. You'll see it used often.
  549. </p>
  550. <p>
  551. § It's worth noting here that in Go the scope of function parameters and return values
  552. is the same as the function body, even though they appear lexically outside the braces
  553. that enclose the body.
  554. </p>
  555. <h3 id="for">For</h3>
  556. <p>
  557. The Go <code>for</code> loop is similar to&mdash;but not the same as&mdash;C's.
  558. It unifies <code>for</code>
  559. and <code>while</code> and there is no <code>do-while</code>.
  560. There are three forms, only one of which has semicolons.
  561. </p>
  562. <pre>
  563. // Like a C for
  564. for init; condition; post { }
  565. // Like a C while
  566. for condition { }
  567. // Like a C for(;;)
  568. for { }
  569. </pre>
  570. <p>
  571. Short declarations make it easy to declare the index variable right in the loop.
  572. </p>
  573. <pre>
  574. sum := 0
  575. for i := 0; i &lt; 10; i++ {
  576. sum += i
  577. }
  578. </pre>
  579. <p>
  580. If you're looping over an array, slice, string, or map,
  581. or reading from a channel, a <code>range</code> clause can
  582. manage the loop.
  583. </p>
  584. <pre>
  585. for key, value := range oldMap {
  586. newMap[key] = value
  587. }
  588. </pre>
  589. <p>
  590. If you only need the first item in the range (the key or index), drop the second:
  591. </p>
  592. <pre>
  593. for key := range m {
  594. if key.expired() {
  595. delete(m, key)
  596. }
  597. }
  598. </pre>
  599. <p>
  600. If you only need the second item in the range (the value), use the <em>blank identifier</em>, an underscore, to discard the first:
  601. </p>
  602. <pre>
  603. sum := 0
  604. for _, value := range array {
  605. sum += value
  606. }
  607. </pre>
  608. <p>
  609. The blank identifier has many uses, as described in <a href="#blank">a later section</a>.
  610. </p>
  611. <p>
  612. For strings, the <code>range</code> does more work for you, breaking out individual
  613. Unicode code points by parsing the UTF-8.
  614. Erroneous encodings consume one byte and produce the
  615. replacement rune U+FFFD.
  616. (The name (with associated builtin type) <code>rune</code> is Go terminology for a
  617. single Unicode code point.
  618. See <a href="/ref/spec#Rune_literals">the language specification</a>
  619. for details.)
  620. The loop
  621. </p>
  622. <pre>
  623. for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
  624. fmt.Printf("character %#U starts at byte position %d\n", char, pos)
  625. }
  626. </pre>
  627. <p>
  628. prints
  629. </p>
  630. <pre>
  631. character U+65E5 '日' starts at byte position 0
  632. character U+672C '本' starts at byte position 3
  633. character U+FFFD '�' starts at byte position 6
  634. character U+8A9E '語' starts at byte position 7
  635. </pre>
  636. <p>
  637. Finally, Go has no comma operator and <code>++</code> and <code>--</code>
  638. are statements not expressions.
  639. Thus if you want to run multiple variables in a <code>for</code>
  640. you should use parallel assignment (although that precludes <code>++</code> and <code>--</code>).
  641. </p>
  642. <pre>
  643. // Reverse a
  644. for i, j := 0, len(a)-1; i &lt; j; i, j = i+1, j-1 {
  645. a[i], a[j] = a[j], a[i]
  646. }
  647. </pre>
  648. <h3 id="switch">Switch</h3>
  649. <p>
  650. Go's <code>switch</code> is more general than C's.
  651. The expressions need not be constants or even integers,
  652. the cases are evaluated top to bottom until a match is found,
  653. and if the <code>switch</code> has no expression it switches on
  654. <code>true</code>.
  655. It's therefore possible&mdash;and idiomatic&mdash;to write an
  656. <code>if</code>-<code>else</code>-<code>if</code>-<code>else</code>
  657. chain as a <code>switch</code>.
  658. </p>
  659. <pre>
  660. func unhex(c byte) byte {
  661. switch {
  662. case '0' &lt;= c &amp;&amp; c &lt;= '9':
  663. return c - '0'
  664. case 'a' &lt;= c &amp;&amp; c &lt;= 'f':
  665. return c - 'a' + 10
  666. case 'A' &lt;= c &amp;&amp; c &lt;= 'F':
  667. return c - 'A' + 10
  668. }
  669. return 0
  670. }
  671. </pre>
  672. <p>
  673. There is no automatic fall through, but cases can be presented
  674. in comma-separated lists.
  675. </p>
  676. <pre>
  677. func shouldEscape(c byte) bool {
  678. switch c {
  679. case ' ', '?', '&amp;', '=', '#', '+', '%':
  680. return true
  681. }
  682. return false
  683. }
  684. </pre>
  685. <p>
  686. Although they are not nearly as common in Go as some other C-like
  687. languages, <code>break</code> statements can be used to terminate
  688. a <code>switch</code> early.
  689. Sometimes, though, it's necessary to break out of a surrounding loop,
  690. not the switch, and in Go that can be accomplished by putting a label
  691. on the loop and "breaking" to that label.
  692. This example shows both uses.
  693. </p>
  694. <pre>
  695. Loop:
  696. for n := 0; n &lt; len(src); n += size {
  697. switch {
  698. case src[n] &lt; sizeOne:
  699. if validateOnly {
  700. break
  701. }
  702. size = 1
  703. update(src[n])
  704. case src[n] &lt; sizeTwo:
  705. if n+1 &gt;= len(src) {
  706. err = errShortInput
  707. break Loop
  708. }
  709. if validateOnly {
  710. break
  711. }
  712. size = 2
  713. update(src[n] + src[n+1]&lt;&lt;shift)
  714. }
  715. }
  716. </pre>
  717. <p>
  718. Of course, the <code>continue</code> statement also accepts an optional label
  719. but it applies only to loops.
  720. </p>
  721. <p>
  722. To close this section, here's a comparison routine for byte slices that uses two
  723. <code>switch</code> statements:
  724. </p>
  725. <pre>
  726. // Compare returns an integer comparing the two byte slices,
  727. // lexicographically.
  728. // The result will be 0 if a == b, -1 if a &lt; b, and +1 if a &gt; b
  729. func Compare(a, b []byte) int {
  730. for i := 0; i &lt; len(a) &amp;&amp; i &lt; len(b); i++ {
  731. switch {
  732. case a[i] &gt; b[i]:
  733. return 1
  734. case a[i] &lt; b[i]:
  735. return -1
  736. }
  737. }
  738. switch {
  739. case len(a) &gt; len(b):
  740. return 1
  741. case len(a) &lt; len(b):
  742. return -1
  743. }
  744. return 0
  745. }
  746. </pre>
  747. <h3 id="type_switch">Type switch</h3>
  748. <p>
  749. A switch can also be used to discover the dynamic type of an interface
  750. variable. Such a <em>type switch</em> uses the syntax of a type
  751. assertion with the keyword <code>type</code> inside the parentheses.
  752. If the switch declares a variable in the expression, the variable will
  753. have the corresponding type in each clause.
  754. It's also idiomatic to reuse the name in such cases, in effect declaring
  755. a new variable with the same name but a different type in each case.
  756. </p>
  757. <pre>
  758. var t interface{}
  759. t = functionOfSomeType()
  760. switch t := t.(type) {
  761. default:
  762. fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
  763. case bool:
  764. fmt.Printf("boolean %t\n", t) // t has type bool
  765. case int:
  766. fmt.Printf("integer %d\n", t) // t has type int
  767. case *bool:
  768. fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
  769. case *int:
  770. fmt.Printf("pointer to integer %d\n", *t) // t has type *int
  771. }
  772. </pre>
  773. <h2 id="functions">Functions</h2>
  774. <h3 id="multiple-returns">Multiple return values</h3>
  775. <p>
  776. One of Go's unusual features is that functions and methods
  777. can return multiple values. This form can be used to
  778. improve on a couple of clumsy idioms in C programs: in-band
  779. error returns such as <code>-1</code> for <code>EOF</code>
  780. and modifying an argument passed by address.
  781. </p>
  782. <p>
  783. In C, a write error is signaled by a negative count with the
  784. error code secreted away in a volatile location.
  785. In Go, <code>Write</code>
  786. can return a count <i>and</i> an error: &ldquo;Yes, you wrote some
  787. bytes but not all of them because you filled the device&rdquo;.
  788. The signature of the <code>Write</code> method on files from
  789. package <code>os</code> is:
  790. </p>
  791. <pre>
  792. func (file *File) Write(b []byte) (n int, err error)
  793. </pre>
  794. <p>
  795. and as the documentation says, it returns the number of bytes
  796. written and a non-nil <code>error</code> when <code>n</code>
  797. <code>!=</code> <code>len(b)</code>.
  798. This is a common style; see the section on error handling for more examples.
  799. </p>
  800. <p>
  801. A similar approach obviates the need to pass a pointer to a return
  802. value to simulate a reference parameter.
  803. Here's a simple-minded function to
  804. grab a number from a position in a byte slice, returning the number
  805. and the next position.
  806. </p>
  807. <pre>
  808. func nextInt(b []byte, i int) (int, int) {
  809. for ; i &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
  810. }
  811. x := 0
  812. for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
  813. x = x*10 + int(b[i]) - '0'
  814. }
  815. return x, i
  816. }
  817. </pre>
  818. <p>
  819. You could use it to scan the numbers in an input slice <code>b</code> like this:
  820. </p>
  821. <pre>
  822. for i := 0; i &lt; len(b); {
  823. x, i = nextInt(b, i)
  824. fmt.Println(x)
  825. }
  826. </pre>
  827. <h3 id="named-results">Named result parameters</h3>
  828. <p>
  829. The return or result "parameters" of a Go function can be given names and
  830. used as regular variables, just like the incoming parameters.
  831. When named, they are initialized to the zero values for their types when
  832. the function begins; if the function executes a <code>return</code> statement
  833. with no arguments, the current values of the result parameters are
  834. used as the returned values.
  835. </p>
  836. <p>
  837. The names are not mandatory but they can make code shorter and clearer:
  838. they're documentation.
  839. If we name the results of <code>nextInt</code> it becomes
  840. obvious which returned <code>int</code>
  841. is which.
  842. </p>
  843. <pre>
  844. func nextInt(b []byte, pos int) (value, nextPos int) {
  845. </pre>
  846. <p>
  847. Because named results are initialized and tied to an unadorned return, they can simplify
  848. as well as clarify. Here's a version
  849. of <code>io.ReadFull</code> that uses them well:
  850. </p>
  851. <pre>
  852. func ReadFull(r Reader, buf []byte) (n int, err error) {
  853. for len(buf) &gt; 0 &amp;&amp; err == nil {
  854. var nr int
  855. nr, err = r.Read(buf)
  856. n += nr
  857. buf = buf[nr:]
  858. }
  859. return
  860. }
  861. </pre>
  862. <h3 id="defer">Defer</h3>
  863. <p>
  864. Go's <code>defer</code> statement schedules a function call (the
  865. <i>deferred</i> function) to be run immediately before the function
  866. executing the <code>defer</code> returns. It's an unusual but
  867. effective way to deal with situations such as resources that must be
  868. released regardless of which path a function takes to return. The
  869. canonical examples are unlocking a mutex or closing a file.
  870. </p>
  871. <pre>
  872. // Contents returns the file's contents as a string.
  873. func Contents(filename string) (string, error) {
  874. f, err := os.Open(filename)
  875. if err != nil {
  876. return "", err
  877. }
  878. defer f.Close() // f.Close will run when we're finished.
  879. var result []byte
  880. buf := make([]byte, 100)
  881. for {
  882. n, err := f.Read(buf[0:])
  883. result = append(result, buf[0:n]...) // append is discussed later.
  884. if err != nil {
  885. if err == io.EOF {
  886. break
  887. }
  888. return "", err // f will be closed if we return here.
  889. }
  890. }
  891. return string(result), nil // f will be closed if we return here.
  892. }
  893. </pre>
  894. <p>
  895. Deferring a call to a function such as <code>Close</code> has two advantages. First, it
  896. guarantees that you will never forget to close the file, a mistake
  897. that's easy to make if you later edit the function to add a new return
  898. path. Second, it means that the close sits near the open,
  899. which is much clearer than placing it at the end of the function.
  900. </p>
  901. <p>
  902. The arguments to the deferred function (which include the receiver if
  903. the function is a method) are evaluated when the <i>defer</i>
  904. executes, not when the <i>call</i> executes. Besides avoiding worries
  905. about variables changing values as the function executes, this means
  906. that a single deferred call site can defer multiple function
  907. executions. Here's a silly example.
  908. </p>
  909. <pre>
  910. for i := 0; i &lt; 5; i++ {
  911. defer fmt.Printf("%d ", i)
  912. }
  913. </pre>
  914. <p>
  915. Deferred functions are executed in LIFO order, so this code will cause
  916. <code>4 3 2 1 0</code> to be printed when the function returns. A
  917. more plausible example is a simple way to trace function execution
  918. through the program. We could write a couple of simple tracing
  919. routines like this:
  920. </p>
  921. <pre>
  922. func trace(s string) { fmt.Println("entering:", s) }
  923. func untrace(s string) { fmt.Println("leaving:", s) }
  924. // Use them like this:
  925. func a() {
  926. trace("a")
  927. defer untrace("a")
  928. // do something....
  929. }
  930. </pre>
  931. <p>
  932. We can do better by exploiting the fact that arguments to deferred
  933. functions are evaluated when the <code>defer</code> executes. The
  934. tracing routine can set up the argument to the untracing routine.
  935. This example:
  936. </p>
  937. <pre>
  938. func trace(s string) string {
  939. fmt.Println("entering:", s)
  940. return s
  941. }
  942. func un(s string) {
  943. fmt.Println("leaving:", s)
  944. }
  945. func a() {
  946. defer un(trace("a"))
  947. fmt.Println("in a")
  948. }
  949. func b() {
  950. defer un(trace("b"))
  951. fmt.Println("in b")
  952. a()
  953. }
  954. func main() {
  955. b()
  956. }
  957. </pre>
  958. <p>
  959. prints
  960. </p>
  961. <pre>
  962. entering: b
  963. in b
  964. entering: a
  965. in a
  966. leaving: a
  967. leaving: b
  968. </pre>
  969. <p>
  970. For programmers accustomed to block-level resource management from
  971. other languages, <code>defer</code> may seem peculiar, but its most
  972. interesting and powerful applications come precisely from the fact
  973. that it's not block-based but function-based. In the section on
  974. <code>panic</code> and <code>recover</code> we'll see another
  975. example of its possibilities.
  976. </p>
  977. <h2 id="data">Data</h2>
  978. <h3 id="allocation_new">Allocation with <code>new</code></h3>
  979. <p>
  980. Go has two allocation primitives, the built-in functions
  981. <code>new</code> and <code>make</code>.
  982. They do different things and apply to different types, which can be confusing,
  983. but the rules are simple.
  984. Let's talk about <code>new</code> first.
  985. It's a built-in function that allocates memory, but unlike its namesakes
  986. in some other languages it does not <em>initialize</em> the memory,
  987. it only <em>zeros</em> it.
  988. That is,
  989. <code>new(T)</code> allocates zeroed storage for a new item of type
  990. <code>T</code> and returns its address, a value of type <code>*T</code>.
  991. In Go terminology, it returns a pointer to a newly allocated zero value of type
  992. <code>T</code>.
  993. </p>
  994. <p>
  995. Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange
  996. when designing your data structures that the
  997. zero value of each type can be used without further initialization. This means a user of
  998. the data structure can create one with <code>new</code> and get right to
  999. work.
  1000. For example, the documentation for <code>bytes.Buffer</code> states that
  1001. "the zero value for <code>Buffer</code> is an empty buffer ready to use."
  1002. Similarly, <code>sync.Mutex</code> does not
  1003. have an explicit constructor or <code>Init</code> method.
  1004. Instead, the zero value for a <code>sync.Mutex</code>
  1005. is defined to be an unlocked mutex.
  1006. </p>
  1007. <p>
  1008. The zero-value-is-useful property works transitively. Consider this type declaration.
  1009. </p>
  1010. <pre>
  1011. type SyncedBuffer struct {
  1012. lock sync.Mutex
  1013. buffer bytes.Buffer
  1014. }
  1015. </pre>
  1016. <p>
  1017. Values of type <code>SyncedBuffer</code> are also ready to use immediately upon allocation
  1018. or just declaration. In the next snippet, both <code>p</code> and <code>v</code> will work
  1019. correctly without further arrangement.
  1020. </p>
  1021. <pre>
  1022. p := new(SyncedBuffer) // type *SyncedBuffer
  1023. var v SyncedBuffer // type SyncedBuffer
  1024. </pre>
  1025. <h3 id="composite_literals">Constructors and composite literals</h3>
  1026. <p>
  1027. Sometimes the zero value isn't good enough and an initializing
  1028. constructor is necessary, as in this example derived from
  1029. package <code>os</code>.
  1030. </p>
  1031. <pre>
  1032. func NewFile(fd int, name string) *File {
  1033. if fd &lt; 0 {
  1034. return nil
  1035. }
  1036. f := new(File)
  1037. f.fd = fd
  1038. f.name = name
  1039. f.dirinfo = nil
  1040. f.nepipe = 0
  1041. return f
  1042. }
  1043. </pre>
  1044. <p>
  1045. There's a lot of boiler plate in there. We can simplify it
  1046. using a <i>composite literal</i>, which is
  1047. an expression that creates a
  1048. new instance each time it is evaluated.
  1049. </p>
  1050. <pre>
  1051. func NewFile(fd int, name string) *File {
  1052. if fd &lt; 0 {
  1053. return nil
  1054. }
  1055. f := File{fd, name, nil, 0}
  1056. return &amp;f
  1057. }
  1058. </pre>
  1059. <p>
  1060. Note that, unlike in C, it's perfectly OK to return the address of a local variable;
  1061. the storage associated with the variable survives after the function
  1062. returns.
  1063. In fact, taking the address of a composite literal
  1064. allocates a fresh instance each time it is evaluated,
  1065. so we can combine these last two lines.
  1066. </p>
  1067. <pre>
  1068. return &amp;File{fd, name, nil, 0}
  1069. </pre>
  1070. <p>
  1071. The fields of a composite literal are laid out in order and must all be present.
  1072. However, by labeling the elements explicitly as <i>field</i><code>:</code><i>value</i>
  1073. pairs, the initializers can appear in any
  1074. order, with the missing ones left as their respective zero values. Thus we could say
  1075. </p>
  1076. <pre>
  1077. return &amp;File{fd: fd, name: name}
  1078. </pre>
  1079. <p>
  1080. As a limiting case, if a composite literal contains no fields at all, it creates
  1081. a zero value for the type. The expressions <code>new(File)</code> and <code>&amp;File{}</code> are equivalent.
  1082. </p>
  1083. <p>
  1084. Composite literals can also be created for arrays, slices, and maps,
  1085. with the field labels being indices or map keys as appropriate.
  1086. In these examples, the initializations work regardless of the values of <code>Enone</code>,
  1087. <code>Eio</code>, and <code>Einval</code>, as long as they are distinct.
  1088. </p>
  1089. <pre>
  1090. a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
  1091. s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
  1092. m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
  1093. </pre>
  1094. <h3 id="allocation_make">Allocation with <code>make</code></h3>
  1095. <p>
  1096. Back to allocation.
  1097. The built-in function <code>make(T, </code><i>args</i><code>)</code> serves
  1098. a purpose different from <code>new(T)</code>.
  1099. It creates slices, maps, and channels only, and it returns an <em>initialized</em>
  1100. (not <em>zeroed</em>)
  1101. value of type <code>T</code> (not <code>*T</code>).
  1102. The reason for the distinction
  1103. is that these three types represent, under the covers, references to data structures that
  1104. must be initialized before use.
  1105. A slice, for example, is a three-item descriptor
  1106. containing a pointer to the data (inside an array), the length, and the
  1107. capacity, and until those items are initialized, the slice is <code>nil</code>.
  1108. For slices, maps, and channels,
  1109. <code>make</code> initializes the internal data structure and prepares
  1110. the value for use.
  1111. For instance,
  1112. </p>
  1113. <pre>
  1114. make([]int, 10, 100)
  1115. </pre>
  1116. <p>
  1117. allocates an array of 100 ints and then creates a slice
  1118. structure with length 10 and a capacity of 100 pointing at the first
  1119. 10 elements of the array.
  1120. (When making a slice, the capacity can be omitted; see the section on slices
  1121. for more information.)
  1122. In contrast, <code>new([]int)</code> returns a pointer to a newly allocated, zeroed slice
  1123. structure, that is, a pointer to a <code>nil</code> slice value.
  1124. </p>
  1125. <p>
  1126. These examples illustrate the difference between <code>new</code> and
  1127. <code>make</code>.
  1128. </p>
  1129. <pre>
  1130. var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
  1131. var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
  1132. // Unnecessarily complex:
  1133. var p *[]int = new([]int)
  1134. *p = make([]int, 100, 100)
  1135. // Idiomatic:
  1136. v := make([]int, 100)
  1137. </pre>
  1138. <p>
  1139. Remember that <code>make</code> applies only to maps, slices and channels
  1140. and does not return a pointer.
  1141. To obtain an explicit pointer allocate with <code>new</code> or take the address
  1142. of a variable explicitly.
  1143. </p>
  1144. <h3 id="arrays">Arrays</h3>
  1145. <p>
  1146. Arrays are useful when planning the detailed layout of memory and sometimes
  1147. can help avoid allocation, but primarily
  1148. they are a building block for slices, the subject of the next section.
  1149. To lay the foundation for that topic, here are a few words about arrays.
  1150. </p>
  1151. <p>
  1152. There are major differences between the ways arrays work in Go and C.
  1153. In Go,
  1154. </p>
  1155. <ul>
  1156. <li>
  1157. Arrays are values. Assigning one array to another copies all the elements.
  1158. </li>
  1159. <li>
  1160. In particular, if you pass an array to a function, it
  1161. will receive a <i>copy</i> of the array, not a pointer to it.
  1162. <li>
  1163. The size of an array is part of its type. The types <code>[10]int</code>
  1164. and <code>[20]int</code> are distinct.
  1165. </li>
  1166. </ul>
  1167. <p>
  1168. The value property can be useful but also expensive; if you want C-like behavior and efficiency,
  1169. you can pass a pointer to the array.
  1170. </p>
  1171. <pre>
  1172. func Sum(a *[3]float64) (sum float64) {
  1173. for _, v := range *a {
  1174. sum += v
  1175. }
  1176. return
  1177. }
  1178. array := [...]float64{7.0, 8.5, 9.1}
  1179. x := Sum(&amp;array) // Note the explicit address-of operator
  1180. </pre>
  1181. <p>
  1182. But even this style isn't idiomatic Go.
  1183. Use slices instead.
  1184. </p>
  1185. <h3 id="slices">Slices</h3>
  1186. <p>
  1187. Slices wrap arrays to give a more general, powerful, and convenient
  1188. interface to sequences of data. Except for items with explicit
  1189. dimension such as transformation matrices, most array programming in
  1190. Go is done with slices rather than simple arrays.
  1191. </p>
  1192. <p>
  1193. Slices hold references to an underlying array, and if you assign one
  1194. slice to another, both refer to the same array.
  1195. If a function takes a slice argument, changes it makes to
  1196. the elements of the slice will be visible to the caller, analogous to
  1197. passing a pointer to the underlying array. A <code>Read</code>
  1198. function can therefore accept a slice argument rather than a pointer
  1199. and a count; the length within the slice sets an upper
  1200. limit of how much data to read. Here is the signature of the
  1201. <code>Read</code> method of the <code>File</code> type in package
  1202. <code>os</code>:
  1203. </p>
  1204. <pre>
  1205. func (f *File) Read(buf []byte) (n int, err error)
  1206. </pre>
  1207. <p>
  1208. The method returns the number of bytes read and an error value, if
  1209. any.
  1210. To read into the first 32 bytes of a larger buffer
  1211. <code>buf</code>, <i>slice</i> (here used as a verb) the buffer.
  1212. </p>
  1213. <pre>
  1214. n, err := f.Read(buf[0:32])
  1215. </pre>
  1216. <p>
  1217. Such slicing is common and efficient. In fact, leaving efficiency aside for
  1218. the moment, the following snippet would also read the first 32 bytes of the buffer.
  1219. </p>
  1220. <pre>
  1221. var n int
  1222. var err error
  1223. for i := 0; i &lt; 32; i++ {
  1224. nbytes, e := f.Read(buf[i:i+1]) // Read one byte.
  1225. if nbytes == 0 || e != nil {
  1226. err = e
  1227. break
  1228. }
  1229. n += nbytes
  1230. }
  1231. </pre>
  1232. <p>
  1233. The length of a slice may be changed as long as it still fits within
  1234. the limits of the underlying array; just assign it to a slice of
  1235. itself. The <i>capacity</i> of a slice, accessible by the built-in
  1236. function <code>cap</code>, reports the maximum length the slice may
  1237. assume. Here is a function to append data to a slice. If the data
  1238. exceeds the capacity, the slice is reallocated. The
  1239. resulting slice is returned. The function uses the fact that
  1240. <code>len</code> and <code>cap</code> are legal when applied to the
  1241. <code>nil</code> slice, and return 0.
  1242. </p>
  1243. <pre>
  1244. func Append(slice, data []byte) []byte {
  1245. l := len(slice)
  1246. if l + len(data) &gt; cap(slice) { // reallocate
  1247. // Allocate double what's needed, for future growth.
  1248. newSlice := make([]byte, (l+len(data))*2)
  1249. // The copy function is predeclared and works for any slice type.
  1250. copy(newSlice, slice)
  1251. slice = newSlice
  1252. }
  1253. slice = slice[0:l+len(data)]
  1254. for i, c := range data {
  1255. slice[l+i] = c
  1256. }
  1257. return slice
  1258. }
  1259. </pre>
  1260. <p>
  1261. We must return the slice afterwards because, although <code>Append</code>
  1262. can modify the elements of <code>slice</code>, the slice itself (the run-time data
  1263. structure holding the pointer, length, and capacity) is passed by value.
  1264. </p>
  1265. <p>
  1266. The idea of appending to a slice is so useful it's captured by the
  1267. <code>append</code> built-in function. To understand that function's
  1268. design, though, we need a little more information, so we'll return
  1269. to it later.
  1270. </p>
  1271. <h3 id="two_dimensional_slices">Two-dimensional slices</h3>
  1272. <p>
  1273. Go's arrays and slices are one-dimensional.
  1274. To create the equivalent of a 2D array or slice, it is necessary to define an array-of-arrays
  1275. or slice-of-slices, like this:
  1276. </p>
  1277. <pre>
  1278. type Transform [3][3]float64 // A 3x3 array, really an array of arrays.
  1279. type LinesOfText [][]byte // A slice of byte slices.
  1280. </pre>
  1281. <p>
  1282. Because slices are variable-length, it is possible to have each inner
  1283. slice be a different length.
  1284. That can be a common situation, as in our <code>LinesOfText</code>
  1285. example: each line has an independent length.
  1286. </p>
  1287. <pre>
  1288. text := LinesOfText{
  1289. []byte("Now is the time"),
  1290. []byte("for all good gophers"),
  1291. []byte("to bring some fun to the party."),
  1292. }
  1293. </pre>
  1294. <p>
  1295. Sometimes it's necessary to allocate a 2D slice, a situation that can arise when
  1296. processing scan lines of pixels, for instance.
  1297. There are two ways to achieve this.
  1298. One is to allocate each slice independently; the other
  1299. is to allocate a single array and point the individual slices into it.
  1300. Which to use depends on your application.
  1301. If the slices might grow or shrink, they should be allocated independently
  1302. to avoid overwriting the next line; if not, it can be more efficient to construct
  1303. the object with a single allocation.
  1304. For reference, here are sketches of the two methods.
  1305. First, a line at a time:
  1306. </p>
  1307. <pre>
  1308. // Allocate the top-level slice.
  1309. picture := make([][]uint8, YSize) // One row per unit of y.
  1310. // Loop over the rows, allocating the slice for each row.
  1311. for i := range picture {
  1312. picture[i] = make([]uint8, XSize)
  1313. }
  1314. </pre>
  1315. <p>
  1316. And now as one allocation, sliced into lines:
  1317. </p>
  1318. <pre>
  1319. // Allocate the top-level slice, the same as before.
  1320. picture := make([][]uint8, YSize) // One row per unit of y.
  1321. // Allocate one large slice to hold all the pixels.
  1322. pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
  1323. // Loop over the rows, slicing each row from the front of the remaining pixels slice.
  1324. for i := range picture {
  1325. picture[i], pixels = pixels[:XSize], pixels[XSize:]
  1326. }
  1327. </pre>
  1328. <h3 id="maps">Maps</h3>
  1329. <p>
  1330. Maps are a convenient and powerful built-in data structure that associate
  1331. values of one type (the <em>key</em>) with values of another type
  1332. (the <em>element</em> or <em>value</em>)
  1333. The key can be of any type for which the equality operator is defined,
  1334. such as integers,
  1335. floating point and complex numbers,
  1336. strings, pointers, interfaces (as long as the dynamic type
  1337. supports equality), structs and arrays.
  1338. Slices cannot be used as map keys,
  1339. because equality is not defined on them.
  1340. Like slices, maps hold references to an underlying data structure.
  1341. If you pass a map to a function
  1342. that changes the contents of the map, the changes will be visible
  1343. in the caller.
  1344. </p>
  1345. <p>
  1346. Maps can be constructed using the usual composite literal syntax
  1347. with colon-separated key-value pairs,
  1348. so it's easy to build them during initialization.
  1349. </p>
  1350. <pre>
  1351. var timeZone = map[string]int{
  1352. "UTC": 0*60*60,
  1353. "EST": -5*60*60,
  1354. "CST": -6*60*60,
  1355. "MST": -7*60*60,
  1356. "PST": -8*60*60,
  1357. }
  1358. </pre>
  1359. <p>
  1360. Assigning and fetching map values looks syntactically just like
  1361. doing the same for arrays and slices except that the index doesn't
  1362. need to be an integer.
  1363. </p>
  1364. <pre>
  1365. offset := timeZone["EST"]
  1366. </pre>
  1367. <p>
  1368. An attempt to fetch a map value with a key that
  1369. is not present in the map will return the zero value for the type
  1370. of the entries
  1371. in the map. For instance, if the map contains integers, looking
  1372. up a non-existent key will return <code>0</code>.
  1373. A set can be implemented as a map with value type <code>bool</code>.
  1374. Set the map entry to <code>true</code> to put the value in the set, and then
  1375. test it by simple indexing.
  1376. </p>
  1377. <pre>
  1378. attended := map[string]bool{
  1379. "Ann": true,
  1380. "Joe": true,
  1381. ...
  1382. }
  1383. if attended[person] { // will be false if person is not in the map
  1384. fmt.Println(person, "was at the meeting")
  1385. }
  1386. </pre>
  1387. <p>
  1388. Sometimes you need to distinguish a missing entry from
  1389. a zero value. Is there an entry for <code>"UTC"</code>
  1390. or is that 0 because it's not in the map at all?
  1391. You can discriminate with a form of multiple assignment.
  1392. </p>
  1393. <pre>
  1394. var seconds int
  1395. var ok bool
  1396. seconds, ok = timeZone[tz]
  1397. </pre>
  1398. <p>
  1399. For obvious reasons this is called the &ldquo;comma ok&rdquo; idiom.
  1400. In this example, if <code>tz</code> is present, <code>seconds</code>
  1401. will be set appropriately and <code>ok</code> will be true; if not,
  1402. <code>seconds</code> will be set to zero and <code>ok</code> will
  1403. be false.
  1404. Here's a function that puts it together with a nice error report:
  1405. </p>
  1406. <pre>
  1407. func offset(tz string) int {
  1408. if seconds, ok := timeZone[tz]; ok {
  1409. return seconds
  1410. }
  1411. log.Println("unknown time zone:", tz)
  1412. return 0
  1413. }
  1414. </pre>
  1415. <p>
  1416. To test for presence in the map without worrying about the actual value,
  1417. you can use the <a href="#blank">blank identifier</a> (<code>_</code>)
  1418. in place of the usual variable for the value.
  1419. </p>
  1420. <pre>
  1421. _, present := timeZone[tz]
  1422. </pre>
  1423. <p>
  1424. To delete a map entry, use the <code>delete</code>
  1425. built-in function, whose arguments are the map and the key to be deleted.
  1426. It's safe to do this even if the key is already absent
  1427. from the map.
  1428. </p>
  1429. <pre>
  1430. delete(timeZone, "PDT") // Now on Standard Time
  1431. </pre>
  1432. <h3 id="printing">Printing</h3>
  1433. <p>
  1434. Formatted printing in Go uses a style similar to C's <code>printf</code>
  1435. family but is richer and more general. The functions live in the <code>fmt</code>
  1436. package and have capitalized names: <code>fmt.Printf</code>, <code>fmt.Fprintf</code>,
  1437. <code>fmt.Sprintf</code> and so on. The string functions (<code>Sprintf</code> etc.)
  1438. return a string rather than filling in a provided buffer.
  1439. </p>
  1440. <p>
  1441. You don't need to provide a format string. For each of <code>Printf</code>,
  1442. <code>Fprintf</code> and <code>Sprintf</code> there is another pair
  1443. of functions, for instance <code>Print</code> and <code>Println</code>.
  1444. These functions do not take a format string but instead generate a default
  1445. format for each argument. The <code>Println</code> versions also insert a blank
  1446. between arguments and append a newline to the output while
  1447. the <code>Print</code> versions add blanks only if the operand on neither side is a string.
  1448. In this example each line produces the same output.
  1449. </p>
  1450. <pre>
  1451. fmt.Printf("Hello %d\n", 23)
  1452. fmt.Fprint(os.Stdout, "Hello ", 23, "\n")
  1453. fmt.Println("Hello", 23)
  1454. fmt.Println(fmt.Sprint("Hello ", 23))
  1455. </pre>
  1456. <p>
  1457. The formatted print functions <code>fmt.Fprint</code>
  1458. and friends take as a first argument any object
  1459. that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code>
  1460. and <code>os.Stderr</code> are familiar instances.
  1461. </p>
  1462. <p>
  1463. Here things start to diverge from C. First, the numeric formats such as <code>%d</code>
  1464. do not take flags for signedness or size; instead, the printing routines use the
  1465. type of the argument to decide these properties.
  1466. </p>
  1467. <pre>
  1468. var x uint64 = 1&lt;&lt;64 - 1
  1469. fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))
  1470. </pre>
  1471. <p>
  1472. prints
  1473. </p>
  1474. <pre>
  1475. 18446744073709551615 ffffffffffffffff; -1 -1
  1476. </pre>
  1477. <p>
  1478. If you just want the default conversion, such as decimal for integers, you can use
  1479. the catchall format <code>%v</code> (for &ldquo;value&rdquo;); the result is exactly
  1480. what <code>Print</code> and <code>Println</code> would produce.
  1481. Moreover, that format can print <em>any</em> value, even arrays, slices, structs, and
  1482. maps. Here is a print statement for the time zone map defined in the previous section.
  1483. </p>
  1484. <pre>
  1485. fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone)
  1486. </pre>
  1487. <p>
  1488. which gives output
  1489. </p>
  1490. <pre>
  1491. map[CST:-21600 PST:-28800 EST:-18000 UTC:0 MST:-25200]
  1492. </pre>
  1493. <p>
  1494. For maps the keys may be output in any order, of course.
  1495. When printing a struct, the modified format <code>%+v</code> annotates the
  1496. fields of the structure with their names, and for any value the alternate
  1497. format <code>%#v</code> prints the value in full Go syntax.
  1498. </p>
  1499. <pre>
  1500. type T struct {
  1501. a int
  1502. b float64
  1503. c string
  1504. }
  1505. t := &amp;T{ 7, -2.35, "abc\tdef" }
  1506. fmt.Printf("%v\n", t)
  1507. fmt.Printf("%+v\n", t)
  1508. fmt.Printf("%#v\n", t)
  1509. fmt.Printf("%#v\n", timeZone)
  1510. </pre>
  1511. <p>
  1512. prints
  1513. </p>
  1514. <pre>
  1515. &amp;{7 -2.35 abc def}
  1516. &amp;{a:7 b:-2.35 c:abc def}
  1517. &amp;main.T{a:7, b:-2.35, c:"abc\tdef"}
  1518. map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200}
  1519. </pre>
  1520. <p>
  1521. (Note the ampersands.)
  1522. That quoted string format is also available through <code>%q</code> when
  1523. applied to a value of type <code>string</code> or <code>[]byte</code>.
  1524. The alternate format <code>%#q</code> will use backquotes instead if possible.
  1525. (The <code>%q</code> format also applies to integers and runes, producing a
  1526. single-quoted rune constant.)
  1527. Also, <code>%x</code> works on strings, byte arrays and byte slices as well as
  1528. on integers, generating a long hexadecimal string, and with
  1529. a space in the format (<code>%&nbsp;x</code>) it puts spaces between the bytes.
  1530. </p>
  1531. <p>
  1532. Another handy format is <code>%T</code>, which prints the <em>type</em> of a value.
  1533. </p>
  1534. <pre>
  1535. fmt.Printf(&quot;%T\n&quot;, timeZone)
  1536. </pre>
  1537. <p>
  1538. prints
  1539. </p>
  1540. <pre>
  1541. map[string] int
  1542. </pre>
  1543. <p>
  1544. If you want to control the default format for a custom type, all that's required is to define
  1545. a method with the signature <code>String() string</code> on the type.
  1546. For our simple type <code>T</code>, that might look like this.
  1547. </p>
  1548. <pre>
  1549. func (t *T) String() string {
  1550. return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
  1551. }
  1552. fmt.Printf("%v\n", t)
  1553. </pre>
  1554. <p>
  1555. to print in the format
  1556. </p>
  1557. <pre>
  1558. 7/-2.35/"abc\tdef"
  1559. </pre>
  1560. <p>
  1561. (If you need to print <em>values</em> of type <code>T</code> as well as pointers to <code>T</code>,
  1562. the receiver for <code>String</code> must be of value type; this example used a pointer because
  1563. that's more efficient and idiomatic for struct types.
  1564. See the section below on <a href="#pointers_vs_values">pointers vs. value receivers</a> for more information.)
  1565. </p>
  1566. <p>
  1567. Our <code>String</code> method is able to call <code>Sprintf</code> because the
  1568. print routines are fully reentrant and can be wrapped this way.
  1569. There is one important detail to understand about this approach,
  1570. however: don't construct a <code>String</code> method by calling
  1571. <code>Sprintf</code> in a way that will recur into your <code>String</code>
  1572. method indefinitely. This can happen if the <code>Sprintf</code>
  1573. call attempts to print the receiver directly as a string, which in
  1574. turn will invoke the method again. It's a common and easy mistake
  1575. to make, as this example shows.
  1576. </p>
  1577. <pre>
  1578. type MyString string
  1579. func (m MyString) String() string {
  1580. return fmt.Sprintf("MyString=%s", m) // Error: will recur forever.
  1581. }
  1582. </pre>
  1583. <p>
  1584. It's also easy to fix: convert the argument to the basic string type, which does not have the
  1585. method.
  1586. </p>
  1587. <pre>
  1588. type MyString string
  1589. func (m MyString) String() string {
  1590. return fmt.Sprintf("MyString=%s", string(m)) // OK: note conversion.
  1591. }
  1592. </pre>
  1593. <p>
  1594. In the <a href="#initialization">initialization section</a> we'll see another technique that avoids this recursion.
  1595. </p>
  1596. <p>
  1597. Another printing technique is to pass a print routine's arguments directly to another such routine.
  1598. The signature of <code>Printf</code> uses the type <code>...interface{}</code>
  1599. for its final argument to specify that an arbitrary number of parameters (of arbitrary type)
  1600. can appear after the format.
  1601. </p>
  1602. <pre>
  1603. func Printf(format string, v ...interface{}) (n int, err error) {
  1604. </pre>
  1605. <p>
  1606. Within the function <code>Printf</code>, <code>v</code> acts like a variable of type
  1607. <code>[]interface{}</code> but if it is passed to another variadic function, it acts like
  1608. a regular list of arguments.
  1609. Here is the implementation of the
  1610. function <code>log.Println</code> we used above. It passes its arguments directly to
  1611. <code>fmt.Sprintln</code> for the actual formatting.
  1612. </p>
  1613. <pre>
  1614. // Println prints to the standard logger in the manner of fmt.Println.
  1615. func Println(v ...interface{}) {
  1616. std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string)
  1617. }
  1618. </pre>
  1619. <p>
  1620. We write <code>...</code> after <code>v</code> in the nested call to <code>Sprintln</code> to tell the
  1621. compiler to treat <code>v</code> as a list of arguments; otherwise it would just pass
  1622. <code>v</code> as a single slice argument.
  1623. </p>
  1624. <p>
  1625. There's even more to printing than we've covered here. See the <code>godoc</code> documentation
  1626. for package <code>fmt</code> for the details.
  1627. </p>
  1628. <p>
  1629. By the way, a <code>...</code> parameter can be of a specific type, for instance <code>...int</code>
  1630. for a min function that chooses the least of a list of integers:
  1631. </p>
  1632. <pre>
  1633. func Min(a ...int) int {
  1634. min := int(^uint(0) &gt;&gt; 1) // largest int
  1635. for _, i := range a {
  1636. if i &lt; min {
  1637. min = i
  1638. }
  1639. }
  1640. return min
  1641. }
  1642. </pre>
  1643. <h3 id="append">Append</h3>
  1644. <p>
  1645. Now we have the missing piece we needed to explain the design of
  1646. the <code>append</code> built-in function. The signature of <code>append</code>
  1647. is different from our custom <code>Append</code> function above.
  1648. Schematically, it's like this:
  1649. </p>
  1650. <pre>
  1651. func append(slice []<i>T</i>, elements ...<i>T</i>) []<i>T</i>
  1652. </pre>
  1653. <p>
  1654. where <i>T</i> is a placeholder for any given type. You can't
  1655. actually write a function in Go where the type <code>T</code>
  1656. is determined by the caller.
  1657. That's why <code>append</code> is built in: it needs support from the
  1658. compiler.
  1659. </p>
  1660. <p>
  1661. What <code>append</code> does is append the elements to the end of
  1662. the slice and return the result. The result needs to be returned
  1663. because, as with our hand-written <code>Append</code>, the underlying
  1664. array may change. This simple example
  1665. </p>
  1666. <pre>
  1667. x := []int{1,2,3}
  1668. x = append(x, 4, 5, 6)
  1669. fmt.Println(x)
  1670. </pre>
  1671. <p>
  1672. prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a
  1673. little like <code>Printf</code>, collecting an arbitrary number of
  1674. arguments.
  1675. </p>
  1676. <p>
  1677. But what if we wanted to do what our <code>Append</code> does and
  1678. append a slice to a slice? Easy: use <code>...</code> at the call
  1679. site, just as we did in the call to <code>Output</code> above. This
  1680. snippet produces identical output to the one above.
  1681. </p>
  1682. <pre>
  1683. x := []int{1,2,3}
  1684. y := []int{4,5,6}
  1685. x = append(x, y...)
  1686. fmt.Println(x)
  1687. </pre>
  1688. <p>
  1689. Without that <code>...</code>, it wouldn't compile because the types
  1690. would be wrong; <code>y</code> is not of type <code>int</code>.
  1691. </p>
  1692. <h2 id="initialization">Initialization</h2>
  1693. <p>
  1694. Although it doesn't look superficially very different from
  1695. initialization in C or C++, initialization in Go is more powerful.
  1696. Complex structures can be built during initialization and the ordering
  1697. issues among initialized objects, even among different packages, are handled
  1698. correctly.
  1699. </p>
  1700. <h3 id="constants">Constants</h3>
  1701. <p>
  1702. Constants in Go are just that&mdash;constant.
  1703. They are created at compile time, even when defined as
  1704. locals in functions,
  1705. and can only be numbers, characters (runes), strings or booleans.
  1706. Because of the compile-time restriction, the expressions
  1707. that define them must be constant expressions,
  1708. evaluatable by the compiler. For instance,
  1709. <code>1&lt;&lt;3</code> is a constant expression, while
  1710. <code>math.Sin(math.Pi/4)</code> is not because
  1711. the function call to <code>math.Sin</code> needs
  1712. to happen at run time.
  1713. </p>
  1714. <p>
  1715. In Go, enumerated constants are created using the <code>iota</code>
  1716. enumerator. Since <code>iota</code> can be part of an expression and
  1717. expressions can be implicitly repeated, it is easy to build intricate
  1718. sets of values.
  1719. </p>
  1720. {{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}}
  1721. <p>
  1722. The ability to attach a method such as <code>String</code> to any
  1723. user-defined type makes it possible for arbitrary values to format themselves
  1724. automatically for printing.
  1725. Although you'll see it most often applied to structs, this technique is also useful for
  1726. scalar types such as floating-point types like <code>ByteSize</code>.
  1727. </p>
  1728. {{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}}
  1729. <p>
  1730. The expression <code>YB</code> prints as <code>1.00YB</code>,
  1731. while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
  1732. </p>
  1733. <p>
  1734. The use here of <code>Sprintf</code>
  1735. to implement <code>ByteSize</code>'s <code>String</code> method is safe
  1736. (avoids recurring indefinitely) not because of a conversion but
  1737. because it calls <code>Sprintf</code> with <code>%f</code>,
  1738. which is not a string format: <code>Sprintf</code> will only call
  1739. the <code>String</code> method when it wants a string, and <code>%f</code>
  1740. wants a floating-point value.
  1741. </p>
  1742. <h3 id="variables">Variables</h3>
  1743. <p>
  1744. Variables can be initialized just like constants but the
  1745. initializer can be a general expression computed at run time.
  1746. </p>
  1747. <pre>
  1748. var (
  1749. home = os.Getenv("HOME")
  1750. user = os.Getenv("USER")
  1751. gopath = os.Getenv("GOPATH")
  1752. )
  1753. </pre>
  1754. <h3 id="init">The init function</h3>
  1755. <p>
  1756. Finally, each source file can define its own niladic <code>init</code> function to
  1757. set up whatever state is required. (Actually each file can have multiple
  1758. <code>init</code> functions.)
  1759. And finally means finally: <code>init</code> is called after all the
  1760. variable declarations in the package have evaluated their initializers,
  1761. and those are evaluated only after all the imported packages have been
  1762. initialized.
  1763. </p>
  1764. <p>
  1765. Besides initializations that cannot be expressed as declarations,
  1766. a common use of <code>init</code> functions is to verify or repair
  1767. correctness of the program state before real execution begins.
  1768. </p>
  1769. <pre>
  1770. func init() {
  1771. if user == "" {
  1772. log.Fatal("$USER not set")
  1773. }
  1774. if home == "" {
  1775. home = "/home/" + user
  1776. }
  1777. if gopath == "" {
  1778. gopath = home + "/go"
  1779. }
  1780. // gopath may be overridden by --gopath flag on command line.
  1781. flag.StringVar(&amp;gopath, "gopath", gopath, "override default GOPATH")
  1782. }
  1783. </pre>
  1784. <h2 id="methods">Methods</h2>
  1785. <h3 id="pointers_vs_values">Pointers vs. Values</h3>
  1786. <p>
  1787. As we saw with <code>ByteSize</code>,
  1788. methods can be defined for any named type (except a pointer or an interface);
  1789. the receiver does not have to be a struct.
  1790. </p>
  1791. <p>
  1792. In the discussion of slices above, we wrote an <code>Append</code>
  1793. function. We can define it as a method on slices instead. To do
  1794. this, we first declare a named type to which we can bind the method, and
  1795. then make the receiver for the method a value of that type.
  1796. </p>
  1797. <pre>
  1798. type ByteSlice []byte
  1799. func (slice ByteSlice) Append(data []byte) []byte {
  1800. // Body exactly the same as the Append function defined above.
  1801. }
  1802. </pre>
  1803. <p>
  1804. This still requires the method to return the updated slice. We can
  1805. eliminate that clumsiness by redefining the method to take a
  1806. <i>pointer</i> to a <code>ByteSlice</code> as its receiver, so the
  1807. method can overwrite the caller's slice.
  1808. </p>
  1809. <pre>
  1810. func (p *ByteSlice) Append(data []byte) {
  1811. slice := *p
  1812. // Body as above, without the return.
  1813. *p = slice
  1814. }
  1815. </pre>
  1816. <p>
  1817. In fact, we can do even better. If we modify our function so it looks
  1818. like a standard <code>Write</code> method, like this,
  1819. </p>
  1820. <pre>
  1821. func (p *ByteSlice) Write(data []byte) (n int, err error) {
  1822. slice := *p
  1823. // Again as above.
  1824. *p = slice
  1825. return len(data), nil
  1826. }
  1827. </pre>
  1828. <p>
  1829. then the type <code>*ByteSlice</code> satisfies the standard interface
  1830. <code>io.Writer</code>, which is handy. For instance, we can
  1831. print into one.
  1832. </p>
  1833. <pre>
  1834. var b ByteSlice
  1835. fmt.Fprintf(&amp;b, "This hour has %d days\n", 7)
  1836. </pre>
  1837. <p>
  1838. We pass the address of a <code>ByteSlice</code>
  1839. because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>.
  1840. The rule about pointers vs. values for receivers is that value methods
  1841. can be invoked on pointers and values, but pointer methods can only be
  1842. invoked on pointers.
  1843. </p>
  1844. <p>
  1845. This rule arises because pointer methods can modify the receiver; invoking
  1846. them on a value would cause the method to receive a copy of the value, so
  1847. any modifications would be discarded.
  1848. The language therefore disallows this mistake.
  1849. There is a handy exception, though. When the value is addressable, the
  1850. language takes care of the common case of invoking a pointer method on a
  1851. value by inserting the address operator automatically.
  1852. In our example, the variable <code>b</code> is addressable, so we can call
  1853. its <code>Write</code> method with just <code>b.Write</code>. The compiler
  1854. will rewrite that to <code>(&amp;b).Write</code> for us.
  1855. </p>
  1856. <p>
  1857. By the way, the idea of using <code>Write</code> on a slice of bytes
  1858. is central to the implementation of <code>bytes.Buffer</code>.
  1859. </p>
  1860. <h2 id="interfaces_and_types">Interfaces and other types</h2>
  1861. <h3 id="interfaces">Interfaces</h3>
  1862. <p>
  1863. Interfaces in Go provide a way to specify the behavior of an
  1864. object: if something can do <em>this</em>, then it can be used
  1865. <em>here</em>. We've seen a couple of simple examples already;
  1866. custom printers can be implemented by a <code>String</code> method
  1867. while <code>Fprintf</code> can generate output to anything
  1868. with a <code>Write</code> method.
  1869. Interfaces with only one or two methods are common in Go code, and are
  1870. usually given a name derived from the method, such as <code>io.Writer</code>
  1871. for something that implements <code>Write</code>.
  1872. </p>
  1873. <p>
  1874. A type can implement multiple interfaces.
  1875. For instance, a collection can be sorted
  1876. by the routines in package <code>sort</code> if it implements
  1877. <code>sort.Interface</code>, which contains <code>Len()</code>,
  1878. <code>Less(i, j int) bool</code>, and <code>Swap(i, j int)</code>,
  1879. and it could also have a custom formatter.
  1880. In this contrived example <code>Sequence</code> satisfies both.
  1881. </p>
  1882. {{code "/doc/progs/eff_sequence.go" `/^type/` "$"}}
  1883. <h3 id="conversions">Conversions</h3>
  1884. <p>
  1885. The <code>String</code> method of <code>Sequence</code> is recreating the
  1886. work that <code>Sprint</code> already does for slices. We can share the
  1887. effort if we convert the <code>Sequence</code> to a plain
  1888. <code>[]int</code> before calling <code>Sprint</code>.
  1889. </p>
  1890. <pre>
  1891. func (s Sequence) String() string {
  1892. sort.Sort(s)
  1893. return fmt.Sprint([]int(s))
  1894. }
  1895. </pre>
  1896. <p>
  1897. This method is another example of the conversion technique for calling
  1898. <code>Sprintf</code> safely from a <code>String</code> method.
  1899. Because the two types (<code>Sequence</code> and <code>[]int</code>)
  1900. are the same if we ignore the type name, it's legal to convert between them.
  1901. The conversion doesn't create a new value, it just temporarily acts
  1902. as though the existing value has a new type.
  1903. (There are other legal conversions, such as from integer to floating point, that
  1904. do create a new value.)
  1905. </p>
  1906. <p>
  1907. It's an idiom in Go programs to convert the
  1908. type of an expression to access a different
  1909. set of methods. As an example, we could use the existing
  1910. type <code>sort.IntSlice</code> to reduce the entire example
  1911. to this:
  1912. </p>
  1913. <pre>
  1914. type Sequence []int
  1915. // Method for printing - sorts the elements before printing
  1916. func (s Sequence) String() string {
  1917. sort.IntSlice(s).Sort()
  1918. return fmt.Sprint([]int(s))
  1919. }
  1920. </pre>
  1921. <p>
  1922. Now, instead of having <code>Sequence</code> implement multiple
  1923. interfaces (sorting and printing), we're using the ability of a data item to be
  1924. converted to multiple types (<code>Sequence</code>, <code>sort.IntSlice</code>
  1925. and <code>[]int</code>), each of which does some part of the job.
  1926. That's more unusual in practice but can be effective.
  1927. </p>
  1928. <h3 id="interface_conversions">Interface conversions and type assertions</h3>
  1929. <p>
  1930. <a href="#type_switch">Type switches</a> are a form of conversion: they take an interface and, for
  1931. each case in the switch, in a sense convert it to the type of that case.
  1932. Here's a simplified version of how the code under <code>fmt.Printf</code> turns a value into
  1933. a string using a type switch.
  1934. If it's already a string, we want the actual string value held by the interface, while if it has a
  1935. <code>String</code> method we want the result of calling the method.
  1936. </p>
  1937. <pre>
  1938. type Stringer interface {
  1939. String() string
  1940. }
  1941. var value interface{} // Value provided by caller.
  1942. switch str := value.(type) {
  1943. case string:
  1944. return str
  1945. case Stringer:
  1946. return str.String()
  1947. }
  1948. </pre>
  1949. <p>
  1950. The first case finds a concrete value; the second converts the interface into another interface.
  1951. It's perfectly fine to mix types this way.
  1952. </p>
  1953. <p>
  1954. What if there's only one type we care about? If we know the value holds a <code>string</code>
  1955. and we just want to extract it?
  1956. A one-case type switch would do, but so would a <em>type assertion</em>.
  1957. A type assertion takes an interface value and extracts from it a value of the specified explicit type.
  1958. The syntax borrows from the clause opening a type switch, but with an explicit
  1959. type rather than the <code>type</code> keyword:
  1960. </p>
  1961. <pre>
  1962. value.(typeName)
  1963. </pre>
  1964. <p>
  1965. and the result is a new value with the static type <code>typeName</code>.
  1966. That type must either be the concrete type held by the interface, or a second interface
  1967. type that the value can be converted to.
  1968. To extract the string we know is in the value, we could write:
  1969. </p>
  1970. <pre>
  1971. str := value.(string)
  1972. </pre>
  1973. <p>
  1974. But if it turns out that the value does not contain a string, the program will crash with a run-time error.
  1975. To guard against that, use the "comma, ok" idiom to test, safely, whether the value is a string:
  1976. </p>
  1977. <pre>
  1978. str, ok := value.(string)
  1979. if ok {
  1980. fmt.Printf("string value is: %q\n", str)
  1981. } else {
  1982. fmt.Printf("value is not a string\n")
  1983. }
  1984. </pre>
  1985. <p>
  1986. If the type assertion fails, <code>str</code> will still exist and be of type string, but it will have
  1987. the zero value, an empty string.
  1988. </p>
  1989. <p>
  1990. As an illustration of the capability, here's an <code>if</code>-<code>else</code>
  1991. statement that's equivalent to the type switch that opened this section.
  1992. </p>
  1993. <pre>
  1994. if str, ok := value.(string); ok {
  1995. return str
  1996. } else if str, ok := value.(Stringer); ok {
  1997. return str.String()
  1998. }
  1999. </pre>
  2000. <h3 id="generality">Generality</h3>
  2001. <p>
  2002. If a type exists only to implement an interface and will
  2003. never have exported methods beyond that interface, there is
  2004. no need to export the type itself.
  2005. Exporting just the interface makes it clear the value has no
  2006. interesting behavior beyond what is described in the
  2007. interface.
  2008. It also avoids the need to repeat the documentation
  2009. on every instance of a common method.
  2010. </p>
  2011. <p>
  2012. In such cases, the constructor should return an interface value
  2013. rather than the implementing type.
  2014. As an example, in the hash libraries
  2015. both <code>crc32.NewIEEE</code> and <code>adler32.New</code>
  2016. return the interface type <code>hash.Hash32</code>.
  2017. Substituting the CRC-32 algorithm for Adler-32 in a Go program
  2018. requires only changing the constructor call;
  2019. the rest of the code is unaffected by the change of algorithm.
  2020. </p>
  2021. <p>
  2022. A similar approach allows the streaming cipher algorithms
  2023. in the various <code>crypto</code> packages to be
  2024. separated from the block ciphers they chain together.
  2025. The <code>Block</code> interface
  2026. in the <code>crypto/cipher</code> package specifies the
  2027. behavior of a block cipher, which provides encryption
  2028. of a single block of data.
  2029. Then, by analogy with the <code>bufio</code> package,
  2030. cipher packages that implement this interface
  2031. can be used to construct streaming ciphers, represented
  2032. by the <code>Stream</code> interface, without
  2033. knowing the details of the block encryption.
  2034. </p>
  2035. <p>
  2036. The <code>crypto/cipher</code> interfaces look like this:
  2037. </p>
  2038. <pre>
  2039. type Block interface {
  2040. BlockSize() int
  2041. Encrypt(src, dst []byte)
  2042. Decrypt(src, dst []byte)
  2043. }
  2044. type Stream interface {
  2045. XORKeyStream(dst, src []byte)
  2046. }
  2047. </pre>
  2048. <p>
  2049. Here's the definition of the counter mode (CTR) stream,
  2050. which turns a block cipher into a streaming cipher; notice
  2051. that the block cipher's details are abstracted away:
  2052. </p>
  2053. <pre>
  2054. // NewCTR returns a Stream that encrypts/decrypts using the given Block in
  2055. // counter mode. The length of iv must be the same as the Block's block size.
  2056. func NewCTR(block Block, iv []byte) Stream
  2057. </pre>
  2058. <p>
  2059. <code>NewCTR</code> applies not
  2060. just to one specific encryption algorithm and data source but to any
  2061. implementation of the <code>Block</code> interface and any
  2062. <code>Stream</code>. Because they return
  2063. interface values, replacing CTR
  2064. encryption with other encryption modes is a localized change. The constructor
  2065. calls must be edited, but because the surrounding code must treat the result only
  2066. as a <code>Stream</code>, it won't notice the difference.
  2067. </p>
  2068. <h3 id="interface_methods">Interfaces and methods</h3>
  2069. <p>
  2070. Since almost anything can have methods attached, almost anything can
  2071. satisfy an interface. One illustrative example is in the <code>http</code>
  2072. package, which defines the <code>Handler</code> interface. Any object
  2073. that implements <code>Handler</code> can serve HTTP requests.
  2074. </p>
  2075. <pre>
  2076. type Handler interface {
  2077. ServeHTTP(ResponseWriter, *Request)
  2078. }
  2079. </pre>
  2080. <p>
  2081. <code>ResponseWriter</code> is itself an interface that provides access
  2082. to the methods needed to return the response to the client.
  2083. Those methods include the standard <code>Write</code> method, so an
  2084. <code>http.ResponseWriter</code> can be used wherever an <code>io.Writer</code>
  2085. can be used.
  2086. <code>Request</code> is a struct containing a parsed representation
  2087. of the request from the client.
  2088. </p>
  2089. <p>
  2090. For brevity, let's ignore POSTs and assume HTTP requests are always
  2091. GETs; that simplification does not affect the way the handlers are
  2092. set up. Here's a trivial but complete implementation of a handler to
  2093. count the number of times the
  2094. page is visited.
  2095. </p>
  2096. <pre>
  2097. // Simple counter server.
  2098. type Counter struct {
  2099. n int
  2100. }
  2101. func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  2102. ctr.n++
  2103. fmt.Fprintf(w, "counter = %d\n", ctr.n)
  2104. }
  2105. </pre>
  2106. <p>
  2107. (Keeping with our theme, note how <code>Fprintf</code> can print to an
  2108. <code>http.ResponseWriter</code>.)
  2109. For reference, here's how to attach such a server to a node on the URL tree.
  2110. </p>
  2111. <pre>
  2112. import "net/http"
  2113. ...
  2114. ctr := new(Counter)
  2115. http.Handle("/counter", ctr)
  2116. </pre>
  2117. <p>
  2118. But why make <code>Counter</code> a struct? An integer is all that's needed.
  2119. (The receiver needs to be a pointer so the increment is visible to the caller.)
  2120. </p>
  2121. <pre>
  2122. // Simpler counter server.
  2123. type Counter int
  2124. func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  2125. *ctr++
  2126. fmt.Fprintf(w, "counter = %d\n", *ctr)
  2127. }
  2128. </pre>
  2129. <p>
  2130. What if your program has some internal state that needs to be notified that a page
  2131. has been visited? Tie a channel to the web page.
  2132. </p>
  2133. <pre>
  2134. // A channel that sends a notification on each visit.
  2135. // (Probably want the channel to be buffered.)
  2136. type Chan chan *http.Request
  2137. func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  2138. ch &lt;- req
  2139. fmt.Fprint(w, "notification sent")
  2140. }
  2141. </pre>
  2142. <p>
  2143. Finally, let's say we wanted to present on <code>/args</code> the arguments
  2144. used when invoking the server binary.
  2145. It's easy to write a function to print the arguments.
  2146. </p>
  2147. <pre>
  2148. func ArgServer() {
  2149. fmt.Println(os.Args)
  2150. }
  2151. </pre>
  2152. <p>
  2153. How do we turn that into an HTTP server? We could make <code>ArgServer</code>
  2154. a method of some type whose value we ignore, but there's a cleaner way.
  2155. Since we can define a method for any type except pointers and interfaces,
  2156. we can write a method for a function.
  2157. The <code>http</code> package contains this code:
  2158. </p>
  2159. <pre>
  2160. // The HandlerFunc type is an adapter to allow the use of
  2161. // ordinary functions as HTTP handlers. If f is a function
  2162. // with the appropriate signature, HandlerFunc(f) is a
  2163. // Handler object that calls f.
  2164. type HandlerFunc func(ResponseWriter, *Request)
  2165. // ServeHTTP calls f(w, req).
  2166. func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) {
  2167. f(w, req)
  2168. }
  2169. </pre>
  2170. <p>
  2171. <code>HandlerFunc</code> is a type with a method, <code>ServeHTTP</code>,
  2172. so values of that type can serve HTTP requests. Look at the implementation
  2173. of the method: the receiver is a function, <code>f</code>, and the method
  2174. calls <code>f</code>. That may seem odd but it's not that different from, say,
  2175. the receiver being a channel and the method sending on the channel.
  2176. </p>
  2177. <p>
  2178. To make <code>ArgServer</code> into an HTTP server, we first modify it
  2179. to have the right signature.
  2180. </p>
  2181. <pre>
  2182. // Argument server.
  2183. func ArgServer(w http.ResponseWriter, req *http.Request) {
  2184. fmt.Fprintln(w, os.Args)
  2185. }
  2186. </pre>
  2187. <p>
  2188. <code>ArgServer</code> now has same signature as <code>HandlerFunc</code>,
  2189. so it can be converted to that type to access its methods,
  2190. just as we converted <code>Sequence</code> to <code>IntSlice</code>
  2191. to access <code>IntSlice.Sort</code>.
  2192. The code to set it up is concise:
  2193. </p>
  2194. <pre>
  2195. http.Handle("/args", http.HandlerFunc(ArgServer))
  2196. </pre>
  2197. <p>
  2198. When someone visits the page <code>/args</code>,
  2199. the handler installed at that page has value <code>ArgServer</code>
  2200. and type <code>HandlerFunc</code>.
  2201. The HTTP server will invoke the method <code>ServeHTTP</code>
  2202. of that type, with <code>ArgServer</code> as the receiver, which will in turn call
  2203. <code>ArgServer</code> (via the invocation <code>f(w, req)</code>
  2204. inside <code>HandlerFunc.ServeHTTP</code>).
  2205. The arguments will then be displayed.
  2206. </p>
  2207. <p>
  2208. In this section we have made an HTTP server from a struct, an integer,
  2209. a channel, and a function, all because interfaces are just sets of
  2210. methods, which can be defined for (almost) any type.
  2211. </p>
  2212. <h2 id="blank">The blank identifier</h2>
  2213. <p>
  2214. We've mentioned the blank identifier a couple of times now, in the context of
  2215. <a href="#for"><code>for</code> <code>range</code> loops</a>
  2216. and <a href="#maps">maps</a>.
  2217. The blank identifier can be assigned or declared with any value of any type, with the
  2218. value discarded harmlessly.
  2219. It's a bit like writing to the Unix <code>/dev/null</code> file:
  2220. it represents a write-only value
  2221. to be used as a place-holder
  2222. where a variable is needed but the actual value is irrelevant.
  2223. It has uses beyond those we've seen already.
  2224. </p>
  2225. <h3 id="blank_assign">The blank identifier in multiple assignment</h3>
  2226. <p>
  2227. The use of a blank identifier in a <code>for</code> <code>range</code> loop is a
  2228. special case of a general situation: multiple assignment.
  2229. </p>
  2230. <p>
  2231. If an assignment requires multiple values on the left side,
  2232. but one of the values will not be used by the program,
  2233. a blank identifier on the left-hand-side of
  2234. the assignment avoids the need
  2235. to create a dummy variable and makes it clear that the
  2236. value is to be discarded.
  2237. For instance, when calling a function that returns
  2238. a value and an error, but only the error is important,
  2239. use the blank identifier to discard the irrelevant value.
  2240. </p>
  2241. <pre>
  2242. if _, err := os.Stat(path); os.IsNotExist(err) {
  2243. fmt.Printf("%s does not exist\n", path)
  2244. }
  2245. </pre>
  2246. <p>
  2247. Occasionally you'll see code that discards the error value in order
  2248. to ignore the error; this is terrible practice. Always check error returns;
  2249. they're provided for a reason.
  2250. </p>
  2251. <pre>
  2252. // Bad! This code will crash if path does not exist.
  2253. fi, _ := os.Stat(path)
  2254. if fi.IsDir() {
  2255. fmt.Printf("%s is a directory\n", path)
  2256. }
  2257. </pre>
  2258. <h3 id="blank_unused">Unused imports and variables</h3>
  2259. <p>
  2260. It is an error to import a package or to declare a variable without using it.
  2261. Unused imports bloat the program and slow compilation,
  2262. while a variable that is initialized but not used is at least
  2263. a wasted computation and perhaps indicative of a
  2264. larger bug.
  2265. When a program is under active development, however,
  2266. unused imports and variables often arise and it can
  2267. be annoying to delete them just to have the compilation proceed,
  2268. only to have them be needed again later.
  2269. The blank identifier provides a workaround.
  2270. </p>
  2271. <p>
  2272. This half-written program has two unused imports
  2273. (<code>fmt</code> and <code>io</code>)
  2274. and an unused variable (<code>fd</code>),
  2275. so it will not compile, but it would be nice to see if the
  2276. code so far is correct.
  2277. </p>
  2278. {{code "/doc/progs/eff_unused1.go" `/package/` `$`}}
  2279. <p>
  2280. To silence complaints about the unused imports, use a
  2281. blank identifier to refer to a symbol from the imported package.
  2282. Similarly, assigning the unused variable <code>fd</code>
  2283. to the blank identifier will silence the unused variable error.
  2284. This version of the program does compile.
  2285. </p>
  2286. {{code "/doc/progs/eff_unused2.go" `/package/` `$`}}
  2287. <p>
  2288. By convention, the global declarations to silence import errors
  2289. should come right after the imports and be commented,
  2290. both to make them easy to find and as a reminder to clean things up later.
  2291. </p>
  2292. <h3 id="blank_import">Import for side effect</h3>
  2293. <p>
  2294. An unused import like <code>fmt</code> or <code>io</code> in the
  2295. previous example should eventually be used or removed:
  2296. blank assignments identify code as a work in progress.
  2297. But sometimes it is useful to import a package only for its
  2298. side effects, without any explicit use.
  2299. For example, during its <code>init</code> function,
  2300. the <code><a href="/pkg/net/http/pprof/">net/http/pprof</a></code>
  2301. package registers HTTP handlers that provide
  2302. debugging information. It has an exported API, but
  2303. most clients need only the handler registration and
  2304. access the data through a web page.
  2305. To import the package only for its side effects, rename the package
  2306. to the blank identifier:
  2307. </p>
  2308. <pre>
  2309. import _ "net/http/pprof"
  2310. </pre>
  2311. <p>
  2312. This form of import makes clear that the package is being
  2313. imported for its side effects, because there is no other possible
  2314. use of the package: in this file, it doesn't have a name.
  2315. (If it did, and we didn't use that name, the compiler would reject the program.)
  2316. </p>
  2317. <h3 id="blank_implements">Interface checks</h3>
  2318. <p>
  2319. As we saw in the discussion of <a href="#interfaces_and_types">interfaces</a> above,
  2320. a type need not declare explicitly that it implements an interface.
  2321. Instead, a type implements the interface just by implementing the interface's methods.
  2322. In practice, most interface conversions are static and therefore checked at compile time.
  2323. For example, passing an <code>*os.File</code> to a function
  2324. expecting an <code>io.Reader</code> will not compile unless
  2325. <code>*os.File</code> implements the <code>io.Reader</code> interface.
  2326. </p>
  2327. <p>
  2328. Some interface checks do happen at run-time, though.
  2329. One instance is in the <code><a href="/pkg/encoding/json/">encoding/json</a></code>
  2330. package, which defines a <code><a href="/pkg/encoding/json/#Marshaler">Marshaler</a></code>
  2331. interface. When the JSON encoder receives a value that implements that interface,
  2332. the encoder invokes the value's marshaling method to convert it to JSON
  2333. instead of doing the standard conversion.
  2334. The encoder checks this property at run time with a <a href="#interface_conversions">type assertion</a> like:
  2335. </p>
  2336. <pre>
  2337. m, ok := val.(json.Marshaler)
  2338. </pre>
  2339. <p>
  2340. If it's necessary only to ask whether a type implements an interface, without
  2341. actually using the interface itself, perhaps as part of an error check, use the blank
  2342. identifier to ignore the type-asserted value:
  2343. </p>
  2344. <pre>
  2345. if _, ok := val.(json.Marshaler); ok {
  2346. fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
  2347. }
  2348. </pre>
  2349. <p>
  2350. One place this situation arises is when it is necessary to guarantee within the package implementing the type that
  2351. it actually satisfies the interface.
  2352. If a type—for example,
  2353. <code><a href="/pkg/encoding/json/#RawMessage">json.RawMessage</a></code>—needs
  2354. a custom JSON representation, it should implement
  2355. <code>json.Marshaler</code>, but there are no static conversions that would
  2356. cause the compiler to verify this automatically.
  2357. If the type inadvertently fails to satisfy the interface, the JSON encoder will still work,
  2358. but will not use the custom implementation.
  2359. To guarantee that the implementation is correct,
  2360. a global declaration using the blank identifier can be used in the package:
  2361. </p>
  2362. <pre>
  2363. var _ json.Marshaler = (*RawMessage)(nil)
  2364. </pre>
  2365. <p>
  2366. In this declaration, the assignment involving a conversion of a
  2367. <code>*RawMessage</code> to a <code>Marshaler</code>
  2368. requires that <code>*RawMessage</code> implements <code>Marshaler</code>,
  2369. and that property will be checked at compile time.
  2370. Should the <code>json.Marshaler</code> interface change, this package
  2371. will no longer compile and we will be on notice that it needs to be updated.
  2372. </p>
  2373. <p>
  2374. The appearance of the blank identifier in this construct indicates that
  2375. the declaration exists only for the type checking,
  2376. not to create a variable.
  2377. Don't do this for every type that satisfies an interface, though.
  2378. By convention, such declarations are only used
  2379. when there are no static conversions already present in the code,
  2380. which is a rare event.
  2381. </p>
  2382. <h2 id="embedding">Embedding</h2>
  2383. <p>
  2384. Go does not provide the typical, type-driven notion of subclassing,
  2385. but it does have the ability to &ldquo;borrow&rdquo; pieces of an
  2386. implementation by <em>embedding</em> types within a struct or
  2387. interface.
  2388. </p>
  2389. <p>
  2390. Interface embedding is very simple.
  2391. We've mentioned the <code>io.Reader</code> and <code>io.Writer</code> interfaces before;
  2392. here are their definitions.
  2393. </p>
  2394. <pre>
  2395. type Reader interface {
  2396. Read(p []byte) (n int, err error)
  2397. }
  2398. type Writer interface {
  2399. Write(p []byte) (n int, err error)
  2400. }
  2401. </pre>
  2402. <p>
  2403. The <code>io</code> package also exports several other interfaces
  2404. that specify objects that can implement several such methods.
  2405. For instance, there is <code>io.ReadWriter</code>, an interface
  2406. containing both <code>Read</code> and <code>Write</code>.
  2407. We could specify <code>io.ReadWriter</code> by listing the
  2408. two methods explicitly, but it's easier and more evocative
  2409. to embed the two interfaces to form the new one, like this:
  2410. </p>
  2411. <pre>
  2412. // ReadWriter is the interface that combines the Reader and Writer interfaces.
  2413. type ReadWriter interface {
  2414. Reader
  2415. Writer
  2416. }
  2417. </pre>
  2418. <p>
  2419. This says just what it looks like: A <code>ReadWriter</code> can do
  2420. what a <code>Reader</code> does <em>and</em> what a <code>Writer</code>
  2421. does; it is a union of the embedded interfaces (which must be disjoint
  2422. sets of methods).
  2423. Only interfaces can be embedded within interfaces.
  2424. </p>
  2425. <p>
  2426. The same basic idea applies to structs, but with more far-reaching
  2427. implications. The <code>bufio</code> package has two struct types,
  2428. <code>bufio.Reader</code> and <code>bufio.Writer</code>, each of
  2429. which of course implements the analogous interfaces from package
  2430. <code>io</code>.
  2431. And <code>bufio</code> also implements a buffered reader/writer,
  2432. which it does by combining a reader and a writer into one struct
  2433. using embedding: it lists the types within the struct
  2434. but does not give them field names.
  2435. </p>
  2436. <pre>
  2437. // ReadWriter stores pointers to a Reader and a Writer.
  2438. // It implements io.ReadWriter.
  2439. type ReadWriter struct {
  2440. *Reader // *bufio.Reader
  2441. *Writer // *bufio.Writer
  2442. }
  2443. </pre>
  2444. <p>
  2445. The embedded elements are pointers to structs and of course
  2446. must be initialized to point to valid structs before they
  2447. can be used.
  2448. The <code>ReadWriter</code> struct could be written as
  2449. </p>
  2450. <pre>
  2451. type ReadWriter struct {
  2452. reader *Reader
  2453. writer *Writer
  2454. }
  2455. </pre>
  2456. <p>
  2457. but then to promote the methods of the fields and to
  2458. satisfy the <code>io</code> interfaces, we would also need
  2459. to provide forwarding methods, like this:
  2460. </p>
  2461. <pre>
  2462. func (rw *ReadWriter) Read(p []byte) (n int, err error) {
  2463. return rw.reader.Read(p)
  2464. }
  2465. </pre>
  2466. <p>
  2467. By embedding the structs directly, we avoid this bookkeeping.
  2468. The methods of embedded types come along for free, which means that <code>bufio.ReadWriter</code>
  2469. not only has the methods of <code>bufio.Reader</code> and <code>bufio.Writer</code>,
  2470. it also satisfies all three interfaces:
  2471. <code>io.Reader</code>,
  2472. <code>io.Writer</code>, and
  2473. <code>io.ReadWriter</code>.
  2474. </p>
  2475. <p>
  2476. There's an important way in which embedding differs from subclassing. When we embed a type,
  2477. the methods of that type become methods of the outer type,
  2478. but when they are invoked the receiver of the method is the inner type, not the outer one.
  2479. In our example, when the <code>Read</code> method of a <code>bufio.ReadWriter</code> is
  2480. invoked, it has exactly the same effect as the forwarding method written out above;
  2481. the receiver is the <code>reader</code> field of the <code>ReadWriter</code>, not the
  2482. <code>ReadWriter</code> itself.
  2483. </p>
  2484. <p>
  2485. Embedding can also be a simple convenience.
  2486. This example shows an embedded field alongside a regular, named field.
  2487. </p>
  2488. <pre>
  2489. type Job struct {
  2490. Command string
  2491. *log.Logger
  2492. }
  2493. </pre>
  2494. <p>
  2495. The <code>Job</code> type now has the <code>Log</code>, <code>Logf</code>
  2496. and other
  2497. methods of <code>*log.Logger</code>. We could have given the <code>Logger</code>
  2498. a field name, of course, but it's not necessary to do so. And now, once
  2499. initialized, we can
  2500. log to the <code>Job</code>:
  2501. </p>
  2502. <pre>
  2503. job.Log("starting now...")
  2504. </pre>
  2505. <p>
  2506. The <code>Logger</code> is a regular field of the <code>Job</code> struct,
  2507. so we can initialize it in the usual way inside the constructor for <code>Job</code>, like this,
  2508. </p>
  2509. <pre>
  2510. func NewJob(command string, logger *log.Logger) *Job {
  2511. return &amp;Job{command, logger}
  2512. }
  2513. </pre>
  2514. <p>
  2515. or with a composite literal,
  2516. </p>
  2517. <pre>
  2518. job := &amp;Job{command, log.New(os.Stderr, "Job: ", log.Ldate)}
  2519. </pre>
  2520. <p>
  2521. If we need to refer to an embedded field directly, the type name of the field,
  2522. ignoring the package qualifier, serves as a field name, as it did
  2523. in the <code>Read</code> method of our <code>ReaderWriter</code> struct.
  2524. Here, if we needed to access the
  2525. <code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>,
  2526. we would write <code>job.Logger</code>,
  2527. which would be useful if we wanted to refine the methods of <code>Logger</code>.
  2528. </p>
  2529. <pre>
  2530. func (job *Job) Logf(format string, args ...interface{}) {
  2531. job.Logger.Logf("%q: %s", job.Command, fmt.Sprintf(format, args...))
  2532. }
  2533. </pre>
  2534. <p>
  2535. Embedding types introduces the problem of name conflicts but the rules to resolve
  2536. them are simple.
  2537. First, a field or method <code>X</code> hides any other item <code>X</code> in a more deeply
  2538. nested part of the type.
  2539. If <code>log.Logger</code> contained a field or method called <code>Command</code>, the <code>Command</code> field
  2540. of <code>Job</code> would dominate it.
  2541. </p>
  2542. <p>
  2543. Second, if the same name appears at the same nesting level, it is usually an error;
  2544. it would be erroneous to embed <code>log.Logger</code> if the <code>Job</code> struct
  2545. contained another field or method called <code>Logger</code>.
  2546. However, if the duplicate name is never mentioned in the program outside the type definition, it is OK.
  2547. This qualification provides some protection against changes made to types embedded from outside; there
  2548. is no problem if a field is added that conflicts with another field in another subtype if neither field
  2549. is ever used.
  2550. </p>
  2551. <h2 id="concurrency">Concurrency</h2>
  2552. <h3 id="sharing">Share by communicating</h3>
  2553. <p>
  2554. Concurrent programming is a large topic and there is space only for some
  2555. Go-specific highlights here.
  2556. </p>
  2557. <p>
  2558. Concurrent programming in many environments is made difficult by the
  2559. subtleties required to implement correct access to shared variables. Go encourages
  2560. a different approach in which shared values are passed around on channels
  2561. and, in fact, never actively shared by separate threads of execution.
  2562. Only one goroutine has access to the value at any given time.
  2563. Data races cannot occur, by design.
  2564. To encourage this way of thinking we have reduced it to a slogan:
  2565. </p>
  2566. <blockquote>
  2567. Do not communicate by sharing memory;
  2568. instead, share memory by communicating.
  2569. </blockquote>
  2570. <p>
  2571. This approach can be taken too far. Reference counts may be best done
  2572. by putting a mutex around an integer variable, for instance. But as a
  2573. high-level approach, using channels to control access makes it easier
  2574. to write clear, correct programs.
  2575. </p>
  2576. <p>
  2577. One way to think about this model is to consider a typical single-threaded
  2578. program running on one CPU. It has no need for synchronization primitives.
  2579. Now run another such instance; it too needs no synchronization. Now let those
  2580. two communicate; if the communication is the synchronizer, there's still no need
  2581. for other synchronization. Unix pipelines, for example, fit this model
  2582. perfectly. Although Go's approach to concurrency originates in Hoare's
  2583. Communicating Sequential Processes (CSP),
  2584. it can also be seen as a type-safe generalization of Unix pipes.
  2585. </p>
  2586. <h3 id="goroutines">Goroutines</h3>
  2587. <p>
  2588. They're called <em>goroutines</em> because the existing
  2589. terms&mdash;threads, coroutines, processes, and so on&mdash;convey
  2590. inaccurate connotations. A goroutine has a simple model: it is a
  2591. function executing concurrently with other goroutines in the same
  2592. address space. It is lightweight, costing little more than the
  2593. allocation of stack space.
  2594. And the stacks start small, so they are cheap, and grow
  2595. by allocating (and freeing) heap storage as required.
  2596. </p>
  2597. <p>
  2598. Goroutines are multiplexed onto multiple OS threads so if one should
  2599. block, such as while waiting for I/O, others continue to run. Their
  2600. design hides many of the complexities of thread creation and
  2601. management.
  2602. </p>
  2603. <p>
  2604. Prefix a function or method call with the <code>go</code>
  2605. keyword to run the call in a new goroutine.
  2606. When the call completes, the goroutine
  2607. exits, silently. (The effect is similar to the Unix shell's
  2608. <code>&amp;</code> notation for running a command in the
  2609. background.)
  2610. </p>
  2611. <pre>
  2612. go list.Sort() // run list.Sort concurrently; don't wait for it.
  2613. </pre>
  2614. <p>
  2615. A function literal can be handy in a goroutine invocation.
  2616. </p>
  2617. <pre>
  2618. func Announce(message string, delay time.Duration) {
  2619. go func() {
  2620. time.Sleep(delay)
  2621. fmt.Println(message)
  2622. }() // Note the parentheses - must call the function.
  2623. }
  2624. </pre>
  2625. <p>
  2626. In Go, function literals are closures: the implementation makes
  2627. sure the variables referred to by the function survive as long as they are active.
  2628. </p>
  2629. <p>
  2630. These examples aren't too practical because the functions have no way of signaling
  2631. completion. For that, we need channels.
  2632. </p>
  2633. <h3 id="channels">Channels</h3>
  2634. <p>
  2635. Like maps, channels are allocated with <code>make</code>, and
  2636. the resulting value acts as a reference to an underlying data structure.
  2637. If an optional integer parameter is provided, it sets the buffer size for the channel.
  2638. The default is zero, for an unbuffered or synchronous channel.
  2639. </p>
  2640. <pre>
  2641. ci := make(chan int) // unbuffered channel of integers
  2642. cj := make(chan int, 0) // unbuffered channel of integers
  2643. cs := make(chan *os.File, 100) // buffered channel of pointers to Files
  2644. </pre>
  2645. <p>
  2646. Unbuffered channels combine communication&mdash;the exchange of a value&mdash;with
  2647. synchronization&mdash;guaranteeing that two calculations (goroutines) are in
  2648. a known state.
  2649. </p>
  2650. <p>
  2651. There are lots of nice idioms using channels. Here's one to get us started.
  2652. In the previous section we launched a sort in the background. A channel
  2653. can allow the launching goroutine to wait for the sort to complete.
  2654. </p>
  2655. <pre>
  2656. c := make(chan int) // Allocate a channel.
  2657. // Start the sort in a goroutine; when it completes, signal on the channel.
  2658. go func() {
  2659. list.Sort()
  2660. c &lt;- 1 // Send a signal; value does not matter.
  2661. }()
  2662. doSomethingForAWhile()
  2663. &lt;-c // Wait for sort to finish; discard sent value.
  2664. </pre>
  2665. <p>
  2666. Receivers always block until there is data to receive.
  2667. If the channel is unbuffered, the sender blocks until the receiver has
  2668. received the value.
  2669. If the channel has a buffer, the sender blocks only until the
  2670. value has been copied to the buffer; if the buffer is full, this
  2671. means waiting until some receiver has retrieved a value.
  2672. </p>
  2673. <p>
  2674. A buffered channel can be used like a semaphore, for instance to
  2675. limit throughput. In this example, incoming requests are passed
  2676. to <code>handle</code>, which sends a value into the channel, processes
  2677. the request, and then receives a value from the channel
  2678. to ready the &ldquo;semaphore&rdquo; for the next consumer.
  2679. The capacity of the channel buffer limits the number of
  2680. simultaneous calls to <code>process</code>.
  2681. </p>
  2682. <pre>
  2683. var sem = make(chan int, MaxOutstanding)
  2684. func handle(r *Request) {
  2685. sem &lt;- 1 // Wait for active queue to drain.
  2686. process(r) // May take a long time.
  2687. &lt;-sem // Done; enable next request to run.
  2688. }
  2689. func Serve(queue chan *Request) {
  2690. for {
  2691. req := &lt;-queue
  2692. go handle(req) // Don't wait for handle to finish.
  2693. }
  2694. }
  2695. </pre>
  2696. <p>
  2697. Once <code>MaxOutstanding</code> handlers are executing <code>process</code>,
  2698. any more will block trying to send into the filled channel buffer,
  2699. until one of the existing handlers finishes and receives from the buffer.
  2700. </p>
  2701. <p>
  2702. This design has a problem, though: <code>Serve</code>
  2703. creates a new goroutine for
  2704. every incoming request, even though only <code>MaxOutstanding</code>
  2705. of them can run at any moment.
  2706. As a result, the program can consume unlimited resources if the requests come in too fast.
  2707. We can address that deficiency by changing <code>Serve</code> to
  2708. gate the creation of the goroutines.
  2709. Here's an obvious solution, but beware it has a bug we'll fix subsequently:
  2710. </p>
  2711. <pre>
  2712. func Serve(queue chan *Request) {
  2713. for req := range queue {
  2714. sem &lt;- 1
  2715. go func() {
  2716. process(req) // Buggy; see explanation below.
  2717. &lt;-sem
  2718. }()
  2719. }
  2720. }</pre>
  2721. <p>
  2722. The bug is that in a Go <code>for</code> loop, the loop variable
  2723. is reused for each iteration, so the <code>req</code>
  2724. variable is shared across all goroutines.
  2725. That's not what we want.
  2726. We need to make sure that <code>req</code> is unique for each goroutine.
  2727. Here's one way to do that, passing the value of <code>req</code> as an argument
  2728. to the closure in the goroutine:
  2729. </p>
  2730. <pre>
  2731. func Serve(queue chan *Request) {
  2732. for req := range queue {
  2733. sem &lt;- 1
  2734. go func(req *Request) {
  2735. process(req)
  2736. &lt;-sem
  2737. }(req)
  2738. }
  2739. }</pre>
  2740. <p>
  2741. Compare this version with the previous to see the difference in how
  2742. the closure is declared and run.
  2743. Another solution is just to create a new variable with the same
  2744. name, as in this example:
  2745. </p>
  2746. <pre>
  2747. func Serve(queue chan *Request) {
  2748. for req := range queue {
  2749. req := req // Create new instance of req for the goroutine.
  2750. sem &lt;- 1
  2751. go func() {
  2752. process(req)
  2753. &lt;-sem
  2754. }()
  2755. }
  2756. }</pre>
  2757. <p>
  2758. It may seem odd to write
  2759. </p>
  2760. <pre>
  2761. req := req
  2762. </pre>
  2763. <p>
  2764. but it's legal and idiomatic in Go to do this.
  2765. You get a fresh version of the variable with the same name, deliberately
  2766. shadowing the loop variable locally but unique to each goroutine.
  2767. </p>
  2768. <p>
  2769. Going back to the general problem of writing the server,
  2770. another approach that manages resources well is to start a fixed
  2771. number of <code>handle</code> goroutines all reading from the request
  2772. channel.
  2773. The number of goroutines limits the number of simultaneous
  2774. calls to <code>process</code>.
  2775. This <code>Serve</code> function also accepts a channel on which
  2776. it will be told to exit; after launching the goroutines it blocks
  2777. receiving from that channel.
  2778. </p>
  2779. <pre>
  2780. func handle(queue chan *Request) {
  2781. for r := range queue {
  2782. process(r)
  2783. }
  2784. }
  2785. func Serve(clientRequests chan *Request, quit chan bool) {
  2786. // Start handlers
  2787. for i := 0; i &lt; MaxOutstanding; i++ {
  2788. go handle(clientRequests)
  2789. }
  2790. &lt;-quit // Wait to be told to exit.
  2791. }
  2792. </pre>
  2793. <h3 id="chan_of_chan">Channels of channels</h3>
  2794. <p>
  2795. One of the most important properties of Go is that
  2796. a channel is a first-class value that can be allocated and passed
  2797. around like any other. A common use of this property is
  2798. to implement safe, parallel demultiplexing.
  2799. </p>
  2800. <p>
  2801. In the example in the previous section, <code>handle</code> was
  2802. an idealized handler for a request but we didn't define the
  2803. type it was handling. If that type includes a channel on which
  2804. to reply, each client can provide its own path for the answer.
  2805. Here's a schematic definition of type <code>Request</code>.
  2806. </p>
  2807. <pre>
  2808. type Request struct {
  2809. args []int
  2810. f func([]int) int
  2811. resultChan chan int
  2812. }
  2813. </pre>
  2814. <p>
  2815. The client provides a function and its arguments, as well as
  2816. a channel inside the request object on which to receive the answer.
  2817. </p>
  2818. <pre>
  2819. func sum(a []int) (s int) {
  2820. for _, v := range a {
  2821. s += v
  2822. }
  2823. return
  2824. }
  2825. request := &amp;Request{[]int{3, 4, 5}, sum, make(chan int)}
  2826. // Send request
  2827. clientRequests &lt;- request
  2828. // Wait for response.
  2829. fmt.Printf("answer: %d\n", &lt;-request.resultChan)
  2830. </pre>
  2831. <p>
  2832. On the server side, the handler function is the only thing that changes.
  2833. </p>
  2834. <pre>
  2835. func handle(queue chan *Request) {
  2836. for req := range queue {
  2837. req.resultChan &lt;- req.f(req.args)
  2838. }
  2839. }
  2840. </pre>
  2841. <p>
  2842. There's clearly a lot more to do to make it realistic, but this
  2843. code is a framework for a rate-limited, parallel, non-blocking RPC
  2844. system, and there's not a mutex in sight.
  2845. </p>
  2846. <h3 id="parallel">Parallelization</h3>
  2847. <p>
  2848. Another application of these ideas is to parallelize a calculation
  2849. across multiple CPU cores. If the calculation can be broken into
  2850. separate pieces that can execute independently, it can be parallelized,
  2851. with a channel to signal when each piece completes.
  2852. </p>
  2853. <p>
  2854. Let's say we have an expensive operation to perform on a vector of items,
  2855. and that the value of the operation on each item is independent,
  2856. as in this idealized example.
  2857. </p>
  2858. <pre>
  2859. type Vector []float64
  2860. // Apply the operation to v[i], v[i+1] ... up to v[n-1].
  2861. func (v Vector) DoSome(i, n int, u Vector, c chan int) {
  2862. for ; i &lt; n; i++ {
  2863. v[i] += u.Op(v[i])
  2864. }
  2865. c &lt;- 1 // signal that this piece is done
  2866. }
  2867. </pre>
  2868. <p>
  2869. We launch the pieces independently in a loop, one per CPU.
  2870. They can complete in any order but it doesn't matter; we just
  2871. count the completion signals by draining the channel after
  2872. launching all the goroutines.
  2873. </p>
  2874. <pre>
  2875. const numCPU = 4 // number of CPU cores
  2876. func (v Vector) DoAll(u Vector) {
  2877. c := make(chan int, numCPU) // Buffering optional but sensible.
  2878. for i := 0; i &lt; numCPU; i++ {
  2879. go v.DoSome(i*len(v)/numCPU, (i+1)*len(v)/numCPU, u, c)
  2880. }
  2881. // Drain the channel.
  2882. for i := 0; i &lt; numCPU; i++ {
  2883. &lt;-c // wait for one task to complete
  2884. }
  2885. // All done.
  2886. }
  2887. </pre>
  2888. <p>
  2889. Rather than create a constant value for numCPU, we can ask the runtime what
  2890. value is appropriate.
  2891. The function <code><a href="/pkg/runtime#NumCPU">runtime.NumCPU</a></code>
  2892. returns the number of hardware CPU cores in the machine, so we could write
  2893. </p>
  2894. <pre>
  2895. var numCPU = runtime.NumCPU()
  2896. </pre>
  2897. <p>
  2898. There is also a function
  2899. <code><a href="/pkg/runtime#GOMAXPROCS">runtime.GOMAXPROCS</a></code>,
  2900. which reports (or sets)
  2901. the user-specified number of cores that a Go program can have running
  2902. simultaneously.
  2903. It defaults to the value of <code>runtime.NumCPU</code> but can be
  2904. overridden by setting the similarly named shell environment variable
  2905. or by calling the function with a positive number. Calling it with
  2906. zero just queries the value.
  2907. Therefore if we want to honor the user's resource request, we should write
  2908. </p>
  2909. <pre>
  2910. var numCPU = runtime.GOMAXPROCS(0)
  2911. </pre>
  2912. <p>
  2913. Be sure not to confuse the ideas of concurrency—structuring a program
  2914. as independently executing components—and parallelism—executing
  2915. calculations in parallel for efficiency on multiple CPUs.
  2916. Although the concurrency features of Go can make some problems easy
  2917. to structure as parallel computations, Go is a concurrent language,
  2918. not a parallel one, and not all parallelization problems fit Go's model.
  2919. For a discussion of the distinction, see the talk cited in
  2920. <a href="//blog.golang.org/2013/01/concurrency-is-not-parallelism.html">this
  2921. blog post</a>.
  2922. <h3 id="leaky_buffer">A leaky buffer</h3>
  2923. <p>
  2924. The tools of concurrent programming can even make non-concurrent
  2925. ideas easier to express. Here's an example abstracted from an RPC
  2926. package. The client goroutine loops receiving data from some source,
  2927. perhaps a network. To avoid allocating and freeing buffers, it keeps
  2928. a free list, and uses a buffered channel to represent it. If the
  2929. channel is empty, a new buffer gets allocated.
  2930. Once the message buffer is ready, it's sent to the server on
  2931. <code>serverChan</code>.
  2932. </p>
  2933. <pre>
  2934. var freeList = make(chan *Buffer, 100)
  2935. var serverChan = make(chan *Buffer)
  2936. func client() {
  2937. for {
  2938. var b *Buffer
  2939. // Grab a buffer if available; allocate if not.
  2940. select {
  2941. case b = &lt;-freeList:
  2942. // Got one; nothing more to do.
  2943. default:
  2944. // None free, so allocate a new one.
  2945. b = new(Buffer)
  2946. }
  2947. load(b) // Read next message from the net.
  2948. serverChan &lt;- b // Send to server.
  2949. }
  2950. }
  2951. </pre>
  2952. <p>
  2953. The server loop receives each message from the client, processes it,
  2954. and returns the buffer to the free list.
  2955. </p>
  2956. <pre>
  2957. func server() {
  2958. for {
  2959. b := &lt;-serverChan // Wait for work.
  2960. process(b)
  2961. // Reuse buffer if there's room.
  2962. select {
  2963. case freeList &lt;- b:
  2964. // Buffer on free list; nothing more to do.
  2965. default:
  2966. // Free list full, just carry on.
  2967. }
  2968. }
  2969. }
  2970. </pre>
  2971. <p>
  2972. The client attempts to retrieve a buffer from <code>freeList</code>;
  2973. if none is available, it allocates a fresh one.
  2974. The server's send to <code>freeList</code> puts <code>b</code> back
  2975. on the free list unless the list is full, in which case the
  2976. buffer is dropped on the floor to be reclaimed by
  2977. the garbage collector.
  2978. (The <code>default</code> clauses in the <code>select</code>
  2979. statements execute when no other case is ready,
  2980. meaning that the <code>selects</code> never block.)
  2981. This implementation builds a leaky bucket free list
  2982. in just a few lines, relying on the buffered channel and
  2983. the garbage collector for bookkeeping.
  2984. </p>
  2985. <h2 id="errors">Errors</h2>
  2986. <p>
  2987. Library routines must often return some sort of error indication to
  2988. the caller.
  2989. As mentioned earlier, Go's multivalue return makes it
  2990. easy to return a detailed error description alongside the normal
  2991. return value.
  2992. It is good style to use this feature to provide detailed error information.
  2993. For example, as we'll see, <code>os.Open</code> doesn't
  2994. just return a <code>nil</code> pointer on failure, it also returns an
  2995. error value that describes what went wrong.
  2996. </p>
  2997. <p>
  2998. By convention, errors have type <code>error</code>,
  2999. a simple built-in interface.
  3000. </p>
  3001. <pre>
  3002. type error interface {
  3003. Error() string
  3004. }
  3005. </pre>
  3006. <p>
  3007. A library writer is free to implement this interface with a
  3008. richer model under the covers, making it possible not only
  3009. to see the error but also to provide some context.
  3010. As mentioned, alongside the usual <code>*os.File</code>
  3011. return value, <code>os.Open</code> also returns an
  3012. error value.
  3013. If the file is opened successfully, the error will be <code>nil</code>,
  3014. but when there is a problem, it will hold an
  3015. <code>os.PathError</code>:
  3016. </p>
  3017. <pre>
  3018. // PathError records an error and the operation and
  3019. // file path that caused it.
  3020. type PathError struct {
  3021. Op string // "open", "unlink", etc.
  3022. Path string // The associated file.
  3023. Err error // Returned by the system call.
  3024. }
  3025. func (e *PathError) Error() string {
  3026. return e.Op + " " + e.Path + ": " + e.Err.Error()
  3027. }
  3028. </pre>
  3029. <p>
  3030. <code>PathError</code>'s <code>Error</code> generates
  3031. a string like this:
  3032. </p>
  3033. <pre>
  3034. open /etc/passwx: no such file or directory
  3035. </pre>
  3036. <p>
  3037. Such an error, which includes the problematic file name, the
  3038. operation, and the operating system error it triggered, is useful even
  3039. if printed far from the call that caused it;
  3040. it is much more informative than the plain
  3041. "no such file or directory".
  3042. </p>
  3043. <p>
  3044. When feasible, error strings should identify their origin, such as by having
  3045. a prefix naming the operation or package that generated the error. For example, in package
  3046. <code>image</code>, the string representation for a decoding error due to an
  3047. unknown format is "image: unknown format".
  3048. </p>
  3049. <p>
  3050. Callers that care about the precise error details can
  3051. use a type switch or a type assertion to look for specific
  3052. errors and extract details. For <code>PathErrors</code>
  3053. this might include examining the internal <code>Err</code>
  3054. field for recoverable failures.
  3055. </p>
  3056. <pre>
  3057. for try := 0; try &lt; 2; try++ {
  3058. file, err = os.Create(filename)
  3059. if err == nil {
  3060. return
  3061. }
  3062. if e, ok := err.(*os.PathError); ok &amp;&amp; e.Err == syscall.ENOSPC {
  3063. deleteTempFiles() // Recover some space.
  3064. continue
  3065. }
  3066. return
  3067. }
  3068. </pre>
  3069. <p>
  3070. The second <code>if</code> statement here is another <a href="#interface_conversions">type assertion</a>.
  3071. If it fails, <code>ok</code> will be false, and <code>e</code>
  3072. will be <code>nil</code>.
  3073. If it succeeds, <code>ok</code> will be true, which means the
  3074. error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
  3075. which we can examine for more information about the error.
  3076. </p>
  3077. <h3 id="panic">Panic</h3>
  3078. <p>
  3079. The usual way to report an error to a caller is to return an
  3080. <code>error</code> as an extra return value. The canonical
  3081. <code>Read</code> method is a well-known instance; it returns a byte
  3082. count and an <code>error</code>. But what if the error is
  3083. unrecoverable? Sometimes the program simply cannot continue.
  3084. </p>
  3085. <p>
  3086. For this purpose, there is a built-in function <code>panic</code>
  3087. that in effect creates a run-time error that will stop the program
  3088. (but see the next section). The function takes a single argument
  3089. of arbitrary type&mdash;often a string&mdash;to be printed as the
  3090. program dies. It's also a way to indicate that something impossible has
  3091. happened, such as exiting an infinite loop.
  3092. </p>
  3093. <pre>
  3094. // A toy implementation of cube root using Newton's method.
  3095. func CubeRoot(x float64) float64 {
  3096. z := x/3 // Arbitrary initial value
  3097. for i := 0; i &lt; 1e6; i++ {
  3098. prevz := z
  3099. z -= (z*z*z-x) / (3*z*z)
  3100. if veryClose(z, prevz) {
  3101. return z
  3102. }
  3103. }
  3104. // A million iterations has not converged; something is wrong.
  3105. panic(fmt.Sprintf("CubeRoot(%g) did not converge", x))
  3106. }
  3107. </pre>
  3108. <p>
  3109. This is only an example but real library functions should
  3110. avoid <code>panic</code>. If the problem can be masked or worked
  3111. around, it's always better to let things continue to run rather
  3112. than taking down the whole program. One possible counterexample
  3113. is during initialization: if the library truly cannot set itself up,
  3114. it might be reasonable to panic, so to speak.
  3115. </p>
  3116. <pre>
  3117. var user = os.Getenv("USER")
  3118. func init() {
  3119. if user == "" {
  3120. panic("no value for $USER")
  3121. }
  3122. }
  3123. </pre>
  3124. <h3 id="recover">Recover</h3>
  3125. <p>
  3126. When <code>panic</code> is called, including implicitly for run-time
  3127. errors such as indexing a slice out of bounds or failing a type
  3128. assertion, it immediately stops execution of the current function
  3129. and begins unwinding the stack of the goroutine, running any deferred
  3130. functions along the way. If that unwinding reaches the top of the
  3131. goroutine's stack, the program dies. However, it is possible to
  3132. use the built-in function <code>recover</code> to regain control
  3133. of the goroutine and resume normal execution.
  3134. </p>
  3135. <p>
  3136. A call to <code>recover</code> stops the unwinding and returns the
  3137. argument passed to <code>panic</code>. Because the only code that
  3138. runs while unwinding is inside deferred functions, <code>recover</code>
  3139. is only useful inside deferred functions.
  3140. </p>
  3141. <p>
  3142. One application of <code>recover</code> is to shut down a failing goroutine
  3143. inside a server without killing the other executing goroutines.
  3144. </p>
  3145. <pre>
  3146. func server(workChan &lt;-chan *Work) {
  3147. for work := range workChan {
  3148. go safelyDo(work)
  3149. }
  3150. }
  3151. func safelyDo(work *Work) {
  3152. defer func() {
  3153. if err := recover(); err != nil {
  3154. log.Println("work failed:", err)
  3155. }
  3156. }()
  3157. do(work)
  3158. }
  3159. </pre>
  3160. <p>
  3161. In this example, if <code>do(work)</code> panics, the result will be
  3162. logged and the goroutine will exit cleanly without disturbing the
  3163. others. There's no need to do anything else in the deferred closure;
  3164. calling <code>recover</code> handles the condition completely.
  3165. </p>
  3166. <p>
  3167. Because <code>recover</code> always returns <code>nil</code> unless called directly
  3168. from a deferred function, deferred code can call library routines that themselves
  3169. use <code>panic</code> and <code>recover</code> without failing. As an example,
  3170. the deferred function in <code>safelyDo</code> might call a logging function before
  3171. calling <code>recover</code>, and that logging code would run unaffected
  3172. by the panicking state.
  3173. </p>
  3174. <p>
  3175. With our recovery pattern in place, the <code>do</code>
  3176. function (and anything it calls) can get out of any bad situation
  3177. cleanly by calling <code>panic</code>. We can use that idea to
  3178. simplify error handling in complex software. Let's look at an
  3179. idealized version of a <code>regexp</code> package, which reports
  3180. parsing errors by calling <code>panic</code> with a local
  3181. error type. Here's the definition of <code>Error</code>,
  3182. an <code>error</code> method, and the <code>Compile</code> function.
  3183. </p>
  3184. <pre>
  3185. // Error is the type of a parse error; it satisfies the error interface.
  3186. type Error string
  3187. func (e Error) Error() string {
  3188. return string(e)
  3189. }
  3190. // error is a method of *Regexp that reports parsing errors by
  3191. // panicking with an Error.
  3192. func (regexp *Regexp) error(err string) {
  3193. panic(Error(err))
  3194. }
  3195. // Compile returns a parsed representation of the regular expression.
  3196. func Compile(str string) (regexp *Regexp, err error) {
  3197. regexp = new(Regexp)
  3198. // doParse will panic if there is a parse error.
  3199. defer func() {
  3200. if e := recover(); e != nil {
  3201. regexp = nil // Clear return value.
  3202. err = e.(Error) // Will re-panic if not a parse error.
  3203. }
  3204. }()
  3205. return regexp.doParse(str), nil
  3206. }
  3207. </pre>
  3208. <p>
  3209. If <code>doParse</code> panics, the recovery block will set the
  3210. return value to <code>nil</code>&mdash;deferred functions can modify
  3211. named return values. It will then check, in the assignment
  3212. to <code>err</code>, that the problem was a parse error by asserting
  3213. that it has the local type <code>Error</code>.
  3214. If it does not, the type assertion will fail, causing a run-time error
  3215. that continues the stack unwinding as though nothing had interrupted
  3216. it.
  3217. This check means that if something unexpected happens, such
  3218. as an index out of bounds, the code will fail even though we
  3219. are using <code>panic</code> and <code>recover</code> to handle
  3220. parse errors.
  3221. </p>
  3222. <p>
  3223. With error handling in place, the <code>error</code> method (because it's a
  3224. method bound to a type, it's fine, even natural, for it to have the same name
  3225. as the builtin <code>error</code> type)
  3226. makes it easy to report parse errors without worrying about unwinding
  3227. the parse stack by hand:
  3228. </p>
  3229. <pre>
  3230. if pos == 0 {
  3231. re.error("'*' illegal at start of expression")
  3232. }
  3233. </pre>
  3234. <p>
  3235. Useful though this pattern is, it should be used only within a package.
  3236. <code>Parse</code> turns its internal <code>panic</code> calls into
  3237. <code>error</code> values; it does not expose <code>panics</code>
  3238. to its client. That is a good rule to follow.
  3239. </p>
  3240. <p>
  3241. By the way, this re-panic idiom changes the panic value if an actual
  3242. error occurs. However, both the original and new failures will be
  3243. presented in the crash report, so the root cause of the problem will
  3244. still be visible. Thus this simple re-panic approach is usually
  3245. sufficient&mdash;it's a crash after all&mdash;but if you want to
  3246. display only the original value, you can write a little more code to
  3247. filter unexpected problems and re-panic with the original error.
  3248. That's left as an exercise for the reader.
  3249. </p>
  3250. <h2 id="web_server">A web server</h2>
  3251. <p>
  3252. Let's finish with a complete Go program, a web server.
  3253. This one is actually a kind of web re-server.
  3254. Google provides a service at
  3255. <a href="http://chart.apis.google.com">http://chart.apis.google.com</a>
  3256. that does automatic formatting of data into charts and graphs.
  3257. It's hard to use interactively, though,
  3258. because you need to put the data into the URL as a query.
  3259. The program here provides a nicer interface to one form of data: given a short piece of text,
  3260. it calls on the chart server to produce a QR code, a matrix of boxes that encode the
  3261. text.
  3262. That image can be grabbed with your cell phone's camera and interpreted as,
  3263. for instance, a URL, saving you typing the URL into the phone's tiny keyboard.
  3264. </p>
  3265. <p>
  3266. Here's the complete program.
  3267. An explanation follows.
  3268. </p>
  3269. {{code "/doc/progs/eff_qr.go" `/package/` `$`}}
  3270. <p>
  3271. The pieces up to <code>main</code> should be easy to follow.
  3272. The one flag sets a default HTTP port for our server. The template
  3273. variable <code>templ</code> is where the fun happens. It builds an HTML template
  3274. that will be executed by the server to display the page; more about
  3275. that in a moment.
  3276. </p>
  3277. <p>
  3278. The <code>main</code> function parses the flags and, using the mechanism
  3279. we talked about above, binds the function <code>QR</code> to the root path
  3280. for the server. Then <code>http.ListenAndServe</code> is called to start the
  3281. server; it blocks while the server runs.
  3282. </p>
  3283. <p>
  3284. <code>QR</code> just receives the request, which contains form data, and
  3285. executes the template on the data in the form value named <code>s</code>.
  3286. </p>
  3287. <p>
  3288. The template package <code>html/template</code> is powerful;
  3289. this program just touches on its capabilities.
  3290. In essence, it rewrites a piece of HTML text on the fly by substituting elements derived
  3291. from data items passed to <code>templ.Execute</code>, in this case the
  3292. form value.
  3293. Within the template text (<code>templateStr</code>),
  3294. double-brace-delimited pieces denote template actions.
  3295. The piece from <code>{{html "{{if .}}"}}</code>
  3296. to <code>{{html "{{end}}"}}</code> executes only if the value of the current data item, called <code>.</code> (dot),
  3297. is non-empty.
  3298. That is, when the string is empty, this piece of the template is suppressed.
  3299. </p>
  3300. <p>
  3301. The two snippets <code>{{html "{{.}}"}}</code> say to show the data presented to
  3302. the template—the query string—on the web page.
  3303. The HTML template package automatically provides appropriate escaping so the
  3304. text is safe to display.
  3305. </p>
  3306. <p>
  3307. The rest of the template string is just the HTML to show when the page loads.
  3308. If this is too quick an explanation, see the <a href="/pkg/html/template/">documentation</a>
  3309. for the template package for a more thorough discussion.
  3310. </p>
  3311. <p>
  3312. And there you have it: a useful web server in a few lines of code plus some
  3313. data-driven HTML text.
  3314. Go is powerful enough to make a lot happen in a few lines.
  3315. </p>
  3316. <!--
  3317. TODO
  3318. <pre>
  3319. verifying implementation
  3320. type Color uint32
  3321. // Check that Color implements image.Color and image.Image
  3322. var _ image.Color = Black
  3323. var _ image.Image = Black
  3324. </pre>
  3325. -->