blob: 91f6d6a86acd775a3e562b4ffc3a8ab5ff9e2170 [file] [log] [blame]
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11001<!--{
Russ Coxa40065a2012-03-08 08:39:20 -05002 "Title": "Effective Go",
3 "Template": true
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11004}-->
Rob Pike69d13b22009-09-29 11:57:28 -07005
Russ Cox94439982009-06-25 09:38:35 -07006<h2 id="introduction">Introduction</h2>
7
8<p>
Rob Pike3e740792009-10-05 14:48:57 -07009Go is a new language. Although it borrows ideas from
10existing languages,
11it has unusual properties that make effective Go programs
Russ Cox24ce19c2009-11-08 01:07:53 -080012different in character from programs written in its relatives.
Rob Pike22140a12009-08-19 13:24:24 -070013A straightforward translation of a C++ or Java program into Go
Rob Pike3e740792009-10-05 14:48:57 -070014is unlikely to produce a satisfactory result&mdash;Java programs
Rob Pike22140a12009-08-19 13:24:24 -070015are written in Java, not Go.
16On the other hand, thinking about the problem from a Go
17perspective could produce a successful but quite different
18program.
19In other words,
20to write Go well, it's important to understand its properties
Rob Pikefe287e72009-08-03 14:07:19 -070021and idioms.
Rob Pike22140a12009-08-19 13:24:24 -070022It's also important to know the established conventions for
23programming in Go, such as naming, formatting, program
24construction, and so on, so that programs you write
25will be easy for other Go programmers to understand.
Rob Pikefe287e72009-08-03 14:07:19 -070026</p>
27
28<p>
Rob Pike22140a12009-08-19 13:24:24 -070029This document gives tips for writing clear, idiomatic Go code.
Andrew Gerranda22b0f82012-03-05 15:30:27 +110030It augments the <a href="/ref/spec">language specification</a>,
Rob Pike7201b0c2012-02-28 13:35:58 +110031the <a href="http://tour.golang.org/">Tour of Go</a>,
32and <a href="/doc/code.html">How to Write Go Code</a>,
33all of which you
Rob Pikeeaf6a342009-07-06 15:15:56 -070034should read first.
Russ Cox94439982009-06-25 09:38:35 -070035</p>
36
Rob Pike99b23a12010-06-18 10:52:37 -070037<h3 id="examples">Examples</h3>
Russ Cox94439982009-06-25 09:38:35 -070038
39<p>
Rob Pike88407262009-10-16 11:13:40 -070040The <a href="/src/pkg/">Go package sources</a>
Russ Cox94439982009-06-25 09:38:35 -070041are intended to serve not
42only as the core library but also as examples of how to
Rob Pike22140a12009-08-19 13:24:24 -070043use the language.
44If you have a question about how to approach a problem or how something
Russ Cox24ce19c2009-11-08 01:07:53 -080045might be implemented, they can provide answers, ideas and
Rob Pike22140a12009-08-19 13:24:24 -070046background.
Russ Cox94439982009-06-25 09:38:35 -070047</p>
48
Russ Cox94439982009-06-25 09:38:35 -070049
50<h2 id="formatting">Formatting</h2>
51
52<p>
53Formatting issues are the most contentious
54but the least consequential.
Rob Pike22140a12009-08-19 13:24:24 -070055People can adapt to different formatting styles
56but it's better if they don't have to, and
57less time is devoted to the topic
58if everyone adheres to the same style.
59The problem is how to approach this Utopia without a long
60prescriptive style guide.
Russ Cox94439982009-06-25 09:38:35 -070061</p>
62
Russ Cox94439982009-06-25 09:38:35 -070063<p>
Rob Pike11e4db72009-08-19 16:39:25 -070064With Go we take an unusual
Rob Pike22140a12009-08-19 13:24:24 -070065approach and let the machine
66take care of most formatting issues.
Rob Pike27836912012-02-04 07:49:51 +110067The <code>gofmt</code> program
Shenghou Ma4d7017d2012-03-05 11:12:58 +110068(also available as <code>go fmt</code>, which
Rob Pike27836912012-02-04 07:49:51 +110069operates at the package level rather than source file level)
70reads a Go program
Rob Pike22140a12009-08-19 13:24:24 -070071and emits the source in a standard style of indentation
72and vertical alignment, retaining and if necessary
73reformatting comments.
74If you want to know how to handle some new layout
75situation, run <code>gofmt</code>; if the answer doesn't
Rob Pike9e2fbe12011-03-09 16:47:40 -080076seem right, rearrange your program (or file a bug about <code>gofmt</code>),
77don't work around it.
Rob Piked1a3b982009-07-31 11:41:30 -070078</p>
79
Rob Piked1a3b982009-07-31 11:41:30 -070080<p>
Rob Pike22140a12009-08-19 13:24:24 -070081As an example, there's no need to spend time lining up
82the comments on the fields of a structure.
83<code>Gofmt</code> will do that for you. Given the
84declaration
Russ Cox94439982009-06-25 09:38:35 -070085</p>
86
Rob Pike22140a12009-08-19 13:24:24 -070087<pre>
88type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +110089 name string // name of the object
90 value int // its value
Rob Pike22140a12009-08-19 13:24:24 -070091}
92</pre>
Russ Cox94439982009-06-25 09:38:35 -070093
94<p>
Russ Cox24ce19c2009-11-08 01:07:53 -080095<code>gofmt</code> will line up the columns:
Russ Cox94439982009-06-25 09:38:35 -070096</p>
97
Rob Pike22140a12009-08-19 13:24:24 -070098<pre>
99type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +1100100 name string // name of the object
101 value int // its value
Rob Pike22140a12009-08-19 13:24:24 -0700102}
103</pre>
Russ Cox94439982009-06-25 09:38:35 -0700104
105<p>
Rob Pike9e2fbe12011-03-09 16:47:40 -0800106All Go code in the standard packages has been formatted with <code>gofmt</code>.
Russ Cox94439982009-06-25 09:38:35 -0700107</p>
108
Russ Cox94439982009-06-25 09:38:35 -0700109
Rob Pike22140a12009-08-19 13:24:24 -0700110<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700111Some formatting details remain. Very briefly,
Russ Cox94439982009-06-25 09:38:35 -0700112</p>
113
Rob Pike22140a12009-08-19 13:24:24 -0700114<dl>
Rob Pike163ecda2009-12-16 12:31:18 +1100115 <dt>Indentation</dt>
116 <dd>We use tabs for indentation and <code>gofmt</code> emits them by default.
117 Use spaces only if you must.
118 </dd>
119 <dt>Line length</dt>
120 <dd>
121 Go has no line length limit. Don't worry about overflowing a punched card.
122 If a line feels too long, wrap it and indent with an extra tab.
123 </dd>
124 <dt>Parentheses</dt>
125 <dd>
126 Go needs fewer parentheses: control structures (<code>if</code>,
Rob Pike4c631292011-07-12 23:45:10 +1000127 <code>for</code>, <code>switch</code>) do not have parentheses in
Rob Pike163ecda2009-12-16 12:31:18 +1100128 their syntax.
129 Also, the operator precedence hierarchy is shorter and clearer, so
Rob Pike22140a12009-08-19 13:24:24 -0700130<pre>
131x&lt;&lt;8 + y&lt;&lt;16
132</pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100133 means what the spacing implies.
134 </dd>
Rob Pike22140a12009-08-19 13:24:24 -0700135</dl>
136
Rob Pike6f89f3f2009-10-20 17:32:16 -0700137<h2 id="commentary">Commentary</h2>
Rob Pike22140a12009-08-19 13:24:24 -0700138
Russ Cox94439982009-06-25 09:38:35 -0700139<p>
Robert Griesemer53440da2009-10-01 14:08:00 -0700140Go provides C-style <code>/* */</code> block comments
Russ Cox94439982009-06-25 09:38:35 -0700141and C++-style <code>//</code> line comments.
Rob Pike11e4db72009-08-19 16:39:25 -0700142Line comments are the norm;
143block comments appear mostly as package comments and
144are also useful to disable large swaths of code.
Russ Cox94439982009-06-25 09:38:35 -0700145</p>
146
Rob Pike11e4db72009-08-19 16:39:25 -0700147<p>
148The program—and web server—<code>godoc</code> processes
149Go source files to extract documentation about the contents of the
150package.
151Comments that appear before top-level declarations, with no intervening newlines,
152are extracted along with the declaration to serve as explanatory text for the item.
153The nature and style of these comments determines the
154quality of the documentation <code>godoc</code> produces.
155</p>
Rob Piked951ce42009-07-31 17:54:00 -0700156
157<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700158Every package should have a <i>package comment</i>, a block
Rob Piked951ce42009-07-31 17:54:00 -0700159comment preceding the package clause.
Rob Pike11e4db72009-08-19 16:39:25 -0700160For multi-file packages, the package comment only needs to be
161present in one file, and any one will do.
162The package comment should introduce the package and
Rob Piked951ce42009-07-31 17:54:00 -0700163provide information relevant to the package as a whole.
Rob Pike11e4db72009-08-19 16:39:25 -0700164It will appear first on the <code>godoc</code> page and
165should set up the detailed documentation that follows.
Rob Piked951ce42009-07-31 17:54:00 -0700166</p>
167
168<pre>
169/*
Nigel Tao6a186d32011-04-20 09:57:05 +1000170 Package regexp implements a simple library for
Rob Pike163ecda2009-12-16 12:31:18 +1100171 regular expressions.
Rob Piked951ce42009-07-31 17:54:00 -0700172
Rob Pike163ecda2009-12-16 12:31:18 +1100173 The syntax of the regular expressions accepted is:
Rob Piked951ce42009-07-31 17:54:00 -0700174
Rob Pike163ecda2009-12-16 12:31:18 +1100175 regexp:
176 concatenation { '|' concatenation }
177 concatenation:
178 { closure }
179 closure:
180 term [ '*' | '+' | '?' ]
181 term:
182 '^'
183 '$'
184 '.'
185 character
186 '[' [ '^' ] character-ranges ']'
187 '(' regexp ')'
Rob Piked951ce42009-07-31 17:54:00 -0700188*/
189package regexp
190</pre>
191
192<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700193If the package is simple, the package comment can be brief.
Rob Piked951ce42009-07-31 17:54:00 -0700194</p>
195
196<pre>
Nigel Tao6a186d32011-04-20 09:57:05 +1000197// Package path implements utility routines for
Rob Piked951ce42009-07-31 17:54:00 -0700198// manipulating slash-separated filename paths.
199</pre>
200
Russ Cox94439982009-06-25 09:38:35 -0700201<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700202Comments do not need extra formatting such as banners of stars.
203The generated output may not even be presented in a fixed-width font, so don't depend
Rob Pike430d4622009-10-20 12:30:39 -0700204on spacing for alignment&mdash;<code>godoc</code>, like <code>gofmt</code>,
Rob Pike11e4db72009-08-19 16:39:25 -0700205takes care of that.
Rob Pike6095ff32011-02-16 22:35:31 -0800206The comments are uninterpreted plain text, so HTML and other
Rob Pike11e4db72009-08-19 16:39:25 -0700207annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should
208not be used.
Rob Pike6095ff32011-02-16 22:35:31 -0800209Depending on the context, <code>godoc</code> might not even
210reformat comments, so make sure they look good straight up:
211use correct spelling, punctuation, and sentence structure,
212fold long lines, and so on.
Russ Cox94439982009-06-25 09:38:35 -0700213</p>
214
215<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700216Inside a package, any comment immediately preceding a top-level declaration
217serves as a <i>doc comment</i> for that declaration.
Russ Cox94439982009-06-25 09:38:35 -0700218Every exported (capitalized) name in a program should
Rob Pike11e4db72009-08-19 16:39:25 -0700219have a doc comment.
Russ Cox94439982009-06-25 09:38:35 -0700220</p>
221
222<p>
Rob Pike7ddbe792010-08-24 12:37:51 +1000223Doc comments work best as complete sentences, which allow
Rob Pike11e4db72009-08-19 16:39:25 -0700224a wide variety of automated presentations.
Russ Cox94439982009-06-25 09:38:35 -0700225The first sentence should be a one-sentence summary that
Rob Pikeb95048f2009-10-13 14:32:21 -0700226starts with the name being declared.
Russ Cox94439982009-06-25 09:38:35 -0700227</p>
228
229<pre>
Rob Pike11e4db72009-08-19 16:39:25 -0700230// Compile parses a regular expression and returns, if successful, a Regexp
231// object that can be used to match against text.
Rob Pike68050ac2011-11-01 21:50:21 -0400232func Compile(str string) (regexp *Regexp, err error) {
Russ Cox94439982009-06-25 09:38:35 -0700233</pre>
234
235<p>
Rob Piked951ce42009-07-31 17:54:00 -0700236Go's declaration syntax allows grouping of declarations.
Rob Pike11e4db72009-08-19 16:39:25 -0700237A single doc comment can introduce a group of related constants or variables.
238Since the whole declaration is presented, such a comment can often be perfunctory.
Rob Piked951ce42009-07-31 17:54:00 -0700239</p>
240
241<pre>
Rob Pike11e4db72009-08-19 16:39:25 -0700242// Error codes returned by failures to parse an expression.
243var (
Rob Pike68050ac2011-11-01 21:50:21 -0400244 ErrInternal = errors.New("regexp: internal error")
245 ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
246 ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
Rob Pike163ecda2009-12-16 12:31:18 +1100247 ...
Rob Piked951ce42009-07-31 17:54:00 -0700248)
249</pre>
250
251<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700252Even for private names, grouping can also indicate relationships between items,
Russ Cox24ce19c2009-11-08 01:07:53 -0800253such as the fact that a set of variables is protected by a mutex.
Rob Piked951ce42009-07-31 17:54:00 -0700254</p>
255
256<pre>
Rob Piked951ce42009-07-31 17:54:00 -0700257var (
Rob Pike163ecda2009-12-16 12:31:18 +1100258 countLock sync.Mutex
259 inputCount uint32
260 outputCount uint32
Rob Pike6c088592010-06-14 22:40:35 -0700261 errorCount uint32
Rob Piked951ce42009-07-31 17:54:00 -0700262)
263</pre>
264
Russ Cox94439982009-06-25 09:38:35 -0700265<h2 id="names">Names</h2>
266
Russ Cox94439982009-06-25 09:38:35 -0700267<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700268Names are as important in Go as in any other language.
269In some cases they even have semantic effect: for instance,
270the visibility of a name outside a package is determined by whether its
Rob Pikec2b64182009-11-01 20:54:11 -0800271first character is upper case.
Rob Pikef0ccd402009-08-20 15:39:41 -0700272It's therefore worth spending a little time talking about naming conventions
273in Go programs.
Russ Cox94439982009-06-25 09:38:35 -0700274</p>
275
Rob Pikef0ccd402009-08-20 15:39:41 -0700276
277<h3 id="package-names">Package names</h3>
Russ Cox94439982009-06-25 09:38:35 -0700278
279<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700280When a package is imported, the package name becomes an accessor for the
281contents. After
282</p>
283
284<pre>
285import "bytes"
286</pre>
287
288<p>
289the importing package can talk about <code>bytes.Buffer</code>. It's
290helpful if everyone using the package can use the same name to refer to
291its contents, which implies that the package name should be good:
292short, concise, evocative. By convention, packages are given
293lower case, single-word names; there should be no need for underscores
294or mixedCaps.
295Err on the side of brevity, since everyone using your
296package will be typing that name.
297And don't worry about collisions <i>a priori</i>.
298The package name is only the default name for imports; it need not be unique
299across all source code, and in the rare case of a collision the
300importing package can choose a different name to use locally.
Rob Pike3e740792009-10-05 14:48:57 -0700301In any case, confusion is rare because the file name in the import
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -0800302determines just which package is being used.
Rob Pikef0ccd402009-08-20 15:39:41 -0700303</p>
304
305<p>
306Another convention is that the package name is the base name of
307its source directory;
Andrew Gerrandfeb9a142011-05-25 11:39:40 +1000308the package in <code>src/pkg/encoding/base64</code>
309is imported as <code>"encoding/base64"</code> but has name <code>base64</code>,
310not <code>encoding_base64</code> and not <code>encodingBase64</code>.
Russ Cox94439982009-06-25 09:38:35 -0700311</p>
312
313<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700314The importer of a package will use the name to refer to its contents
315(the <code>import .</code> notation is intended mostly for tests and other
Rob Pike9e2fbe12011-03-09 16:47:40 -0800316unusual situations and should be avoided unless necessary),
317so exported names in the package can use that fact
Rob Pikef0ccd402009-08-20 15:39:41 -0700318to avoid stutter.
319For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>,
320not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>,
321which is a clear, concise name.
322Moreover,
323because imported entities are always addressed with their package name, <code>bufio.Reader</code>
324does not conflict with <code>io.Reader</code>.
Rob Pikeacf4dd42009-12-02 13:46:02 -0800325Similarly, the function to make new instances of <code>ring.Ring</code>&mdash;which
Russ Cox24ce19c2009-11-08 01:07:53 -0800326is the definition of a <em>constructor</em> in Go&mdash;would
Rob Pikeacf4dd42009-12-02 13:46:02 -0800327normally be called <code>NewRing</code>, but since
328<code>Ring</code> is the only type exported by the package, and since the
Rob Pike9e2fbe12011-03-09 16:47:40 -0800329package is called <code>ring</code>, it's called just <code>New</code>,
330which clients of the package see as <code>ring.New</code>.
Rob Pikef0ccd402009-08-20 15:39:41 -0700331Use the package structure to help you choose good names.
Russ Cox94439982009-06-25 09:38:35 -0700332</p>
333
Rob Pikef0ccd402009-08-20 15:39:41 -0700334<p>
335Another short example is <code>once.Do</code>;
336<code>once.Do(setup)</code> reads well and would not be improved by
337writing <code>once.DoOrWaitUntilDone(setup)</code>.
338Long names don't automatically make things more readable.
339If the name represents something intricate or subtle, it's usually better
340to write a helpful doc comment than to attempt to put all the information
341into the name.
342</p>
343
Rob Pike9e2fbe12011-03-09 16:47:40 -0800344<h3 id="Getters">Getters</h3>
345
346<p>
347Go doesn't provide automatic support for getters and setters.
348There's nothing wrong with providing getters and setters yourself,
349and it's often appropriate to do so, but it's neither idiomatic nor necessary
350to put <code>Get</code> into the getter's name. If you have a field called
351<code>owner</code> (lower case, unexported), the getter method should be
352called <code>Owner</code> (upper case, exported), not <code>GetOwner</code>.
353The use of upper-case names for export provides the hook to discriminate
354the field from the method.
355A setter function, if needed, will likely be called <code>SetOwner</code>.
356Both names read well in practice:
357</p>
358<pre>
359owner := obj.Owner()
360if owner != user {
Rob Pikee3d2a292011-06-16 00:13:18 +1000361 obj.SetOwner(user)
Rob Pike9e2fbe12011-03-09 16:47:40 -0800362}
363</pre>
364
Rob Pikef0ccd402009-08-20 15:39:41 -0700365<h3 id="interface-names">Interface names</h3>
Russ Cox94439982009-06-25 09:38:35 -0700366
367<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700368By convention, one-method interfaces are named by
Russ Cox94439982009-06-25 09:38:35 -0700369the method name plus the -er suffix: <code>Reader</code>,
Rob Pikef0ccd402009-08-20 15:39:41 -0700370<code>Writer</code>, <code>Formatter</code> etc.
Russ Cox94439982009-06-25 09:38:35 -0700371</p>
372
Russ Cox94439982009-06-25 09:38:35 -0700373<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700374There are a number of such names and it's productive to honor them and the function
375names they capture.
376<code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>,
377<code>String</code> and so on have
Russ Cox94439982009-06-25 09:38:35 -0700378canonical signatures and meanings. To avoid confusion,
379don't give your method one of those names unless it
380has the same signature and meaning.
381Conversely, if your type implements a method with the
382same meaning as a method on a well-known type,
Rob Pikef0ccd402009-08-20 15:39:41 -0700383give it the same name and signature;
384call your string-converter method <code>String</code> not <code>ToString</code>.
Russ Cox94439982009-06-25 09:38:35 -0700385</p>
386
Rob Pikef0ccd402009-08-20 15:39:41 -0700387<h3 id="mixed-caps">MixedCaps</h3>
388
Russ Cox94439982009-06-25 09:38:35 -0700389<p>
Rob Pike3e740792009-10-05 14:48:57 -0700390Finally, the convention in Go is to use <code>MixedCaps</code>
Rob Pikef0ccd402009-08-20 15:39:41 -0700391or <code>mixedCaps</code> rather than underscores to write
392multiword names.
Russ Cox94439982009-06-25 09:38:35 -0700393</p>
394
Rob Pikec4099762009-08-23 14:00:28 -0700395<h2 id="semicolons">Semicolons</h2>
Russ Cox94439982009-06-25 09:38:35 -0700396
397<p>
Rob Pike163ecda2009-12-16 12:31:18 +1100398Like C, Go's formal grammar uses semicolons to terminate statements;
399unlike C, those semicolons do not appear in the source.
400Instead the lexer uses a simple rule to insert semicolons automatically
401as it scans, so the input text is mostly free of them.
Russ Cox94439982009-06-25 09:38:35 -0700402</p>
403
Rob Pike163ecda2009-12-16 12:31:18 +1100404<p>
405The rule is this. If the last token before a newline is an identifier
406(which includes words like <code>int</code> and <code>float64</code>),
407a basic literal such as a number or string constant, or one of the
408tokens
409</p>
Rob Piked951ce42009-07-31 17:54:00 -0700410<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100411break continue fallthrough return ++ -- ) }
412</pre>
413<p>
414the lexer always inserts a semicolon after the token.
415This could be summarized as, &ldquo;if the newline comes
Rob Pike4c631292011-07-12 23:45:10 +1000416after a token that could end a statement, insert a semicolon&rdquo;.
Rob Pike163ecda2009-12-16 12:31:18 +1100417</p>
418
419<p>
420A semicolon can also be omitted immediately before a closing brace,
421so a statement such as
422</p>
423<pre>
Rob Pikec4099762009-08-23 14:00:28 -0700424 go func() { for { dst &lt;- &lt;-src } }()
Rob Pike22140a12009-08-19 13:24:24 -0700425</pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100426<p>
427needs no semicolons.
428Idiomatic Go programs have semicolons only in places such as
429<code>for</code> loop clauses, to separate the initializer, condition, and
430continuation elements. They are also necessary to separate multiple
431statements on a line, should you write code that way.
432</p>
Rob Pike401c0b32009-08-13 11:29:05 -0700433
Russ Cox94439982009-06-25 09:38:35 -0700434<p>
Rob Pike163ecda2009-12-16 12:31:18 +1100435One caveat. You should never put the opening brace of a
436control structure (<code>if</code>, <code>for</code>, <code>switch</code>,
437or <code>select</code>) on the next line. If you do, a semicolon
438will be inserted before the brace, which could cause unwanted
439effects. Write them like this
Rob Pikec4099762009-08-23 14:00:28 -0700440</p>
441
442<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100443if i &lt; f() {
Rob Pike163ecda2009-12-16 12:31:18 +1100444 g()
Rob Pikec4099762009-08-23 14:00:28 -0700445}
Rob Pike163ecda2009-12-16 12:31:18 +1100446</pre>
447<p>
448not like this
449</p>
450<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100451if i &lt; f() // wrong!
Rob Pike163ecda2009-12-16 12:31:18 +1100452{ // wrong!
453 g()
454}
Rob Pikec4099762009-08-23 14:00:28 -0700455</pre>
456
Rob Pikec4099762009-08-23 14:00:28 -0700457
458<h2 id="control-structures">Control structures</h2>
459
460<p>
Rob Pike6c088592010-06-14 22:40:35 -0700461The control structures of Go are related to those of C but differ
Rob Pikec4099762009-08-23 14:00:28 -0700462in important ways.
463There is no <code>do</code> or <code>while</code> loop, only a
464slightly generalized
465<code>for</code>;
466<code>switch</code> is more flexible;
467<code>if</code> and <code>switch</code> accept an optional
468initialization statement like that of <code>for</code>;
469and there are new control structures including a type switch and a
470multiway communications multiplexer, <code>select</code>.
Rob Pike3e740792009-10-05 14:48:57 -0700471The syntax is also slightly different:
Rob Pike4c631292011-07-12 23:45:10 +1000472there are no parentheses
Rob Pikec4099762009-08-23 14:00:28 -0700473and the bodies must always be brace-delimited.
474</p>
475
476<h3 id="if">If</h3>
477
478<p>
479In Go a simple <code>if</code> looks like this:
480</p>
481<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100482if x &gt; 0 {
Rob Pikec4099762009-08-23 14:00:28 -0700483 return y
484}
485</pre>
486
487<p>
488Mandatory braces encourage writing simple <code>if</code> statements
489on multiple lines. It's good style to do so anyway,
490especially when the body contains a control statement such as a
491<code>return</code> or <code>break</code>.
492</p>
493
494<p>
495Since <code>if</code> and <code>switch</code> accept an initialization
Rob Pikeb95048f2009-10-13 14:32:21 -0700496statement, it's common to see one used to set up a local variable.
Rob Pikec4099762009-08-23 14:00:28 -0700497</p>
498
499<pre>
500if err := file.Chmod(0664); err != nil {
Rob Pikee787f8272010-10-12 16:56:50 -0700501 log.Print(err)
Rob Pike163ecda2009-12-16 12:31:18 +1100502 return err
Rob Pikec4099762009-08-23 14:00:28 -0700503}
504</pre>
505
506<p id="else">
507In the Go libraries, you'll find that
508when an <code>if</code> statement doesn't flow into the next statement—that is,
Rob Piked1a3b982009-07-31 11:41:30 -0700509the body ends in <code>break</code>, <code>continue</code>,
Rob Pikec4099762009-08-23 14:00:28 -0700510<code>goto</code>, or <code>return</code>—the unnecessary
511<code>else</code> is omitted.
Russ Cox94439982009-06-25 09:38:35 -0700512</p>
513
514<pre>
Rob Pike121b4282011-05-08 14:04:42 -0700515f, err := os.Open(name)
Russ Cox94439982009-06-25 09:38:35 -0700516if err != nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100517 return err
Russ Cox94439982009-06-25 09:38:35 -0700518}
Rob Pike163ecda2009-12-16 12:31:18 +1100519codeUsing(f)
Russ Cox94439982009-06-25 09:38:35 -0700520</pre>
521
Rob Pikec4099762009-08-23 14:00:28 -0700522<p>
Rob Pike9e2fbe12011-03-09 16:47:40 -0800523This is an example of a common situation where code must guard against a
524sequence of error conditions. The code reads well if the
Rob Pikec4099762009-08-23 14:00:28 -0700525successful flow of control runs down the page, eliminating error cases
526as they arise. Since error cases tend to end in <code>return</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700527statements, the resulting code needs no <code>else</code> statements.
Rob Pikec4099762009-08-23 14:00:28 -0700528</p>
529
530<pre>
Rob Pike121b4282011-05-08 14:04:42 -0700531f, err := os.Open(name)
Rob Pikec4099762009-08-23 14:00:28 -0700532if err != nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100533 return err
Rob Pikec4099762009-08-23 14:00:28 -0700534}
Rob Pike163ecda2009-12-16 12:31:18 +1100535d, err := f.Stat()
Rob Pikec4099762009-08-23 14:00:28 -0700536if err != nil {
Rob Pikea41006f2011-12-20 14:15:35 -0800537 f.Close()
Rob Pike163ecda2009-12-16 12:31:18 +1100538 return err
Rob Pikec4099762009-08-23 14:00:28 -0700539}
Rob Pike163ecda2009-12-16 12:31:18 +1100540codeUsing(f, d)
Rob Pikec4099762009-08-23 14:00:28 -0700541</pre>
542
543
Rob Pikea41006f2011-12-20 14:15:35 -0800544<h3 id="redeclaration">Redeclaration</h3>
545
546<p>
547An aside: The last example in the previous section demonstrates a detail of how the
548<code>:=</code> short declaration form works.
549The declaration that calls <code>os.Open</code> reads,
550</p>
551
552<pre>
553f, err := os.Open(name)
554</pre>
555
556<p>
557This statement declares two variables, <code>f</code> and <code>err</code>.
558A few lines later, the call to <code>f.Stat</code> reads,
559</p>
560
561<pre>
562d, err := f.Stat()
563</pre>
564
565<p>
566which looks as if it declares <code>d</code> and <code>err</code>.
567Notice, though, that <code>err</code> appears in both statements.
568This duplication is legal: <code>err</code> is declared by the first statement,
569but only <em>re-assigned</em> in the second.
570This means that the call to <code>f.Stat</code> uses the existing
571<code>err</code> variable declared above, and just gives it a new value.
572</p>
573
574<p>
575In a <code>:=</code> declaration a variable <code>v</code> may appear even
576if it has already been declared, provided:
577</p>
578
579<ul>
580<li>this declaration is in the same scope as the existing declaration of <code>v</code>
581(if <code>v</code> is already declared in an outer scope, the declaration will create a new variable),</li>
582<li>the corresponding value in the initialization is assignable to <code>v</code>, and</li>
583<li>there is at least one other variable in the declaration that is being declared anew.</li>
584</ul>
585
586<p>
587This unusual property is pure pragmatism,
588making it easy to use a single <code>err</code> value, for example,
589in a long <code>if-else</code> chain.
590You'll see it used often.
591</p>
592
Rob Pike8aec6122009-09-02 16:41:41 -0700593<h3 id="for">For</h3>
594
595<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700596The Go <code>for</code> loop is similar to&mdash;but not the same as&mdash;C's.
Rob Pike8aec6122009-09-02 16:41:41 -0700597It unifies <code>for</code>
598and <code>while</code> and there is no <code>do-while</code>.
Rob Pikeb95048f2009-10-13 14:32:21 -0700599There are three forms, only one of which has semicolons.
Rob Pike8aec6122009-09-02 16:41:41 -0700600</p>
601<pre>
Rob Pikec77c3b02009-09-08 17:11:57 -0700602// Like a C for
Rob Pike8aec6122009-09-02 16:41:41 -0700603for init; condition; post { }
604
Rob Pikec77c3b02009-09-08 17:11:57 -0700605// Like a C while
Rob Pike8aec6122009-09-02 16:41:41 -0700606for condition { }
607
608// Like a C for(;;)
609for { }
610</pre>
611
612<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700613Short declarations make it easy to declare the index variable right in the loop.
Rob Pike8aec6122009-09-02 16:41:41 -0700614</p>
615<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100616sum := 0
Rob Pike77f6f162009-12-25 07:13:14 +1100617for i := 0; i &lt; 10; i++ {
Rob Pike8aec6122009-09-02 16:41:41 -0700618 sum += i
619}
620</pre>
621
622<p>
Rob Pikec2b64182009-11-01 20:54:11 -0800623If you're looping over an array, slice, string, or map,
624or reading from a channel, a <code>range</code> clause can
Rob Pike4c631292011-07-12 23:45:10 +1000625manage the loop.
Rob Pike8aec6122009-09-02 16:41:41 -0700626</p>
627<pre>
Rob Pike40747952012-03-25 11:34:51 +1100628for key, value := range oldMap {
629 newMap[key] = value
630}
631</pre>
632
633<p>
634If you only need the first item in the range (the key or index), drop the second:
635</p>
636<pre>
637for key := range m {
638 if expired(key) {
639 delete(m, key)
640 }
641}
642</pre>
643
644<p>
645If you only need the second item in the range (the value), use the <em>blank identifier</em>, an underscore, to discard the first:
646</p>
647<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100648sum := 0
Rob Pike40747952012-03-25 11:34:51 +1100649for _, value := range array {
Rob Pike8aec6122009-09-02 16:41:41 -0700650 sum += value
651}
652</pre>
653
654<p>
Rob Pikec2b64182009-11-01 20:54:11 -0800655For strings, the <code>range</code> does more work for you, breaking out individual
Rob Pike9e2fbe12011-03-09 16:47:40 -0800656Unicode characters by parsing the UTF-8.
657Erroneous encodings consume one byte and produce the
658replacement rune U+FFFD. The loop
Rob Pikec77c3b02009-09-08 17:11:57 -0700659</p>
660<pre>
661for pos, char := range "日本語" {
662 fmt.Printf("character %c starts at byte position %d\n", char, pos)
663}
664</pre>
665<p>
666prints
667</p>
668<pre>
669character 日 starts at byte position 0
670character 本 starts at byte position 3
671character 語 starts at byte position 6
672</pre>
673
674<p>
Rob Pike9e2fbe12011-03-09 16:47:40 -0800675Finally, Go has no comma operator and <code>++</code> and <code>--</code>
676are statements not expressions.
677Thus if you want to run multiple variables in a <code>for</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700678you should use parallel assignment.
Rob Pike8aec6122009-09-02 16:41:41 -0700679</p>
680<pre>
681// Reverse a
Rob Pike77f6f162009-12-25 07:13:14 +1100682for i, j := 0, len(a)-1; i &lt; j; i, j = i+1, j-1 {
Rob Pike163ecda2009-12-16 12:31:18 +1100683 a[i], a[j] = a[j], a[i]
Rob Pike8aec6122009-09-02 16:41:41 -0700684}
685</pre>
686
Russ Cox94439982009-06-25 09:38:35 -0700687<h3 id="switch">Switch</h3>
688
689<p>
Rob Pikeeaf6a342009-07-06 15:15:56 -0700690Go's <code>switch</code> is more general than C's.
Rob Pikec4099762009-08-23 14:00:28 -0700691The expressions need not be constants or even integers,
692the cases are evaluated top to bottom until a match is found,
693and if the <code>switch</code> has no expression it switches on
694<code>true</code>.
Rob Pikeb95048f2009-10-13 14:32:21 -0700695It's therefore possible&mdash;and idiomatic&mdash;to write an
Rob Pikec4099762009-08-23 14:00:28 -0700696<code>if</code>-<code>else</code>-<code>if</code>-<code>else</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700697chain as a <code>switch</code>.
Russ Cox94439982009-06-25 09:38:35 -0700698</p>
699
Rob Pikeeaf6a342009-07-06 15:15:56 -0700700<pre>
701func unhex(c byte) byte {
702 switch {
703 case '0' &lt;= c &amp;&amp; c &lt;= '9':
704 return c - '0'
705 case 'a' &lt;= c &amp;&amp; c &lt;= 'f':
706 return c - 'a' + 10
707 case 'A' &lt;= c &amp;&amp; c &lt;= 'F':
708 return c - 'A' + 10
709 }
710 return 0
711}
712</pre>
713
Rob Pikec4099762009-08-23 14:00:28 -0700714<p>
715There is no automatic fall through, but cases can be presented
Rob Pikeb95048f2009-10-13 14:32:21 -0700716in comma-separated lists.
Oling Cate93891f2012-09-18 08:50:24 -0700717</p>
Rob Pikeeaf6a342009-07-06 15:15:56 -0700718<pre>
719func shouldEscape(c byte) bool {
720 switch c {
721 case ' ', '?', '&amp;', '=', '#', '+', '%':
722 return true
723 }
724 return false
725}
726</pre>
727
Rob Pikec4099762009-08-23 14:00:28 -0700728<p>
729Here's a comparison routine for byte arrays that uses two
730<code>switch</code> statements:
Oling Cate93891f2012-09-18 08:50:24 -0700731</p>
Russ Cox94439982009-06-25 09:38:35 -0700732<pre>
Rob Pike40747952012-03-25 11:34:51 +1100733// Compare returns an integer comparing the two byte arrays,
Rob Piked951ce42009-07-31 17:54:00 -0700734// lexicographically.
Rob Pikec4099762009-08-23 14:00:28 -0700735// The result will be 0 if a == b, -1 if a &lt; b, and +1 if a &gt; b
Russ Cox94439982009-06-25 09:38:35 -0700736func Compare(a, b []byte) int {
737 for i := 0; i &lt; len(a) &amp;&amp; i &lt; len(b); i++ {
738 switch {
739 case a[i] &gt; b[i]:
740 return 1
741 case a[i] &lt; b[i]:
742 return -1
743 }
744 }
745 switch {
746 case len(a) &lt; len(b):
747 return -1
748 case len(a) &gt; len(b):
749 return 1
750 }
751 return 0
752}
753</pre>
754
Rob Piked2228692009-10-12 21:18:23 -0700755<p>
756A switch can also be used to discover the dynamic type of an interface
757variable. Such a <em>type switch</em> uses the syntax of a type
758assertion with the keyword <code>type</code> inside the parentheses.
759If the switch declares a variable in the expression, the variable will
760have the corresponding type in each clause.
761</p>
762<pre>
763switch t := interfaceValue.(type) {
764default:
Rob Pike163ecda2009-12-16 12:31:18 +1100765 fmt.Printf("unexpected type %T", t) // %T prints type
Rob Piked2228692009-10-12 21:18:23 -0700766case bool:
Rob Pike163ecda2009-12-16 12:31:18 +1100767 fmt.Printf("boolean %t\n", t)
Rob Piked2228692009-10-12 21:18:23 -0700768case int:
Rob Pike163ecda2009-12-16 12:31:18 +1100769 fmt.Printf("integer %d\n", t)
Rob Piked2228692009-10-12 21:18:23 -0700770case *bool:
Rob Pike163ecda2009-12-16 12:31:18 +1100771 fmt.Printf("pointer to boolean %t\n", *t)
Rob Piked2228692009-10-12 21:18:23 -0700772case *int:
Rob Pike163ecda2009-12-16 12:31:18 +1100773 fmt.Printf("pointer to integer %d\n", *t)
Rob Piked2228692009-10-12 21:18:23 -0700774}
775</pre>
776
Rob Pikea5d6f832009-09-14 10:40:44 -0700777<h2 id="functions">Functions</h2>
778
779<h3 id="multiple-returns">Multiple return values</h3>
780
781<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -0800782One of Go's unusual features is that functions and methods
Rob Pike9e2fbe12011-03-09 16:47:40 -0800783can return multiple values. This form can be used to
Rob Pike3e740792009-10-05 14:48:57 -0700784improve on a couple of clumsy idioms in C programs: in-band
Rob Pikec2b64182009-11-01 20:54:11 -0800785error returns (such as <code>-1</code> for <code>EOF</code>)
Rob Pikea5d6f832009-09-14 10:40:44 -0700786and modifying an argument.
787</p>
788
789<p>
Russ Cox24ce19c2009-11-08 01:07:53 -0800790In C, a write error is signaled by a negative count with the
Rob Pikea5d6f832009-09-14 10:40:44 -0700791error code secreted away in a volatile location.
792In Go, <code>Write</code>
Russ Cox24ce19c2009-11-08 01:07:53 -0800793can return a count <i>and</i> an error: &ldquo;Yes, you wrote some
794bytes but not all of them because you filled the device&rdquo;.
Shenghou Ma0532f4d2012-03-21 09:33:55 -0700795The signature of <code>File.Write</code> in package <code>os</code> is:
Rob Pikea5d6f832009-09-14 10:40:44 -0700796</p>
797
798<pre>
Rob Pike68050ac2011-11-01 21:50:21 -0400799func (file *File) Write(b []byte) (n int, err error)
Rob Pikea5d6f832009-09-14 10:40:44 -0700800</pre>
801
802<p>
803and as the documentation says, it returns the number of bytes
Rob Pike68050ac2011-11-01 21:50:21 -0400804written and a non-nil <code>error</code> when <code>n</code>
Rob Pikea5d6f832009-09-14 10:40:44 -0700805<code>!=</code> <code>len(b)</code>.
806This is a common style; see the section on error handling for more examples.
807</p>
808
809<p>
810A similar approach obviates the need to pass a pointer to a return
Rob Pike3e740792009-10-05 14:48:57 -0700811value to simulate a reference parameter.
812Here's a simple-minded function to
Rob Pikea5d6f832009-09-14 10:40:44 -0700813grab a number from a position in a byte array, returning the number
814and the next position.
815</p>
816
817<pre>
818func nextInt(b []byte, i int) (int, int) {
Rob Pike77f6f162009-12-25 07:13:14 +1100819 for ; i &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
Rob Pike163ecda2009-12-16 12:31:18 +1100820 }
821 x := 0
Rob Pike77f6f162009-12-25 07:13:14 +1100822 for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
Rob Pike163ecda2009-12-16 12:31:18 +1100823 x = x*10 + int(b[i])-'0'
824 }
825 return x, i
Rob Pikea5d6f832009-09-14 10:40:44 -0700826}
827</pre>
828
829<p>
830You could use it to scan the numbers in an input array <code>a</code> like this:
831</p>
832
833<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100834 for i := 0; i &lt; len(a); {
Rob Pike163ecda2009-12-16 12:31:18 +1100835 x, i = nextInt(a, i)
836 fmt.Println(x)
837 }
Rob Pikea5d6f832009-09-14 10:40:44 -0700838</pre>
839
840<h3 id="named-results">Named result parameters</h3>
841
842<p>
843The return or result "parameters" of a Go function can be given names and
844used as regular variables, just like the incoming parameters.
Rob Pike3e740792009-10-05 14:48:57 -0700845When named, they are initialized to the zero values for their types when
Rob Pikea5d6f832009-09-14 10:40:44 -0700846the function begins; if the function executes a <code>return</code> statement
Robert Griesemer53440da2009-10-01 14:08:00 -0700847with no arguments, the current values of the result parameters are
Rob Pikea5d6f832009-09-14 10:40:44 -0700848used as the returned values.
849</p>
850
851<p>
852The names are not mandatory but they can make code shorter and clearer:
853they're documentation.
854If we name the results of <code>nextInt</code> it becomes
855obvious which returned <code>int</code>
856is which.
857</p>
858
859<pre>
860func nextInt(b []byte, pos int) (value, nextPos int) {
861</pre>
862
863<p>
864Because named results are initialized and tied to an unadorned return, they can simplify
865as well as clarify. Here's a version
866of <code>io.ReadFull</code> that uses them well:
867</p>
868
869<pre>
Rob Pike68050ac2011-11-01 21:50:21 -0400870func ReadFull(r Reader, buf []byte) (n int, err error) {
Rob Pike77f6f162009-12-25 07:13:14 +1100871 for len(buf) &gt; 0 &amp;&amp; err == nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100872 var nr int
873 nr, err = r.Read(buf)
874 n += nr
Rob Piked1a3eda2011-08-21 09:46:19 +1000875 buf = buf[nr:]
Rob Pike163ecda2009-12-16 12:31:18 +1100876 }
877 return
Rob Pikea5d6f832009-09-14 10:40:44 -0700878}
879</pre>
880
Rob Pike050905b2010-06-16 13:47:36 -0700881<h3 id="defer">Defer</h3>
882
883<p>
884Go's <code>defer</code> statement schedules a function call (the
885<i>deferred</i> function) to be run immediately before the function
886executing the <code>defer</code> returns. It's an unusual but
887effective way to deal with situations such as resources that must be
888released regardless of which path a function takes to return. The
889canonical examples are unlocking a mutex or closing a file.
890</p>
891
892<pre>
893// Contents returns the file's contents as a string.
Rob Pike68050ac2011-11-01 21:50:21 -0400894func Contents(filename string) (string, error) {
Rob Pike121b4282011-05-08 14:04:42 -0700895 f, err := os.Open(filename)
Rob Pike050905b2010-06-16 13:47:36 -0700896 if err != nil {
897 return "", err
898 }
899 defer f.Close() // f.Close will run when we're finished.
900
901 var result []byte
902 buf := make([]byte, 100)
903 for {
904 n, err := f.Read(buf[0:])
Kyle Consalus009aebd2010-12-01 11:59:13 -0800905 result = append(result, buf[0:n]...) // append is discussed later.
Rob Pike050905b2010-06-16 13:47:36 -0700906 if err != nil {
Vincent Vanackereeb1717e2011-11-03 14:01:30 -0700907 if err == io.EOF {
Rob Pike050905b2010-06-16 13:47:36 -0700908 break
909 }
910 return "", err // f will be closed if we return here.
911 }
912 }
913 return string(result), nil // f will be closed if we return here.
914}
915</pre>
916
917<p>
Rob Pike9e2fbe12011-03-09 16:47:40 -0800918Deferring a call to a function such as <code>Close</code> has two advantages. First, it
Rob Pike050905b2010-06-16 13:47:36 -0700919guarantees that you will never forget to close the file, a mistake
920that's easy to make if you later edit the function to add a new return
921path. Second, it means that the close sits near the open,
922which is much clearer than placing it at the end of the function.
923</p>
924
925<p>
Rob Pikee787f8272010-10-12 16:56:50 -0700926The arguments to the deferred function (which include the receiver if
Rob Pike050905b2010-06-16 13:47:36 -0700927the function is a method) are evaluated when the <i>defer</i>
928executes, not when the <i>call</i> executes. Besides avoiding worries
929about variables changing values as the function executes, this means
930that a single deferred call site can defer multiple function
931executions. Here's a silly example.
932</p>
933
934<pre>
Robert Griesemer76f32282011-02-04 08:43:21 -0800935for i := 0; i &lt; 5; i++ {
Rob Pike050905b2010-06-16 13:47:36 -0700936 defer fmt.Printf("%d ", i)
937}
938</pre>
939
940<p>
941Deferred functions are executed in LIFO order, so this code will cause
942<code>4 3 2 1 0</code> to be printed when the function returns. A
943more plausible example is a simple way to trace function execution
944through the program. We could write a couple of simple tracing
945routines like this:
946</p>
947
948<pre>
949func trace(s string) { fmt.Println("entering:", s) }
950func untrace(s string) { fmt.Println("leaving:", s) }
951
952// Use them like this:
953func a() {
954 trace("a")
955 defer untrace("a")
956 // do something....
957}
958</pre>
959
960<p>
961We can do better by exploiting the fact that arguments to deferred
962functions are evaluated when the <code>defer</code> executes. The
963tracing routine can set up the argument to the untracing routine.
964This example:
965</p>
966
967<pre>
968func trace(s string) string {
969 fmt.Println("entering:", s)
970 return s
971}
972
973func un(s string) {
974 fmt.Println("leaving:", s)
975}
976
977func a() {
978 defer un(trace("a"))
979 fmt.Println("in a")
980}
981
982func b() {
983 defer un(trace("b"))
984 fmt.Println("in b")
985 a()
986}
987
988func main() {
989 b()
990}
991</pre>
992
993<p>
994prints
995</p>
996
997<pre>
998entering: b
999in b
1000entering: a
1001in a
1002leaving: a
1003leaving: b
1004</pre>
1005
1006<p>
1007For programmers accustomed to block-level resource management from
1008other languages, <code>defer</code> may seem peculiar, but its most
1009interesting and powerful applications come precisely from the fact
Rob Pike9e2fbe12011-03-09 16:47:40 -08001010that it's not block-based but function-based. In the section on
1011<code>panic</code> and <code>recover</code> we'll see another
1012example of its possibilities.
Rob Pike050905b2010-06-16 13:47:36 -07001013</p>
1014
Rob Pike2e5a1362009-09-27 17:59:36 -07001015<h2 id="data">Data</h2>
1016
Rob Pike46f482a2011-05-25 06:44:09 +10001017<h3 id="allocation_new">Allocation with <code>new</code></h3>
Rob Pike2e5a1362009-09-27 17:59:36 -07001018
1019<p>
Rob Pike46f482a2011-05-25 06:44:09 +10001020Go has two allocation primitives, the built-in functions
1021<code>new</code> and <code>make</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -07001022They do different things and apply to different types, which can be confusing,
1023but the rules are simple.
Rob Pike46f482a2011-05-25 06:44:09 +10001024Let's talk about <code>new</code> first.
Rob Pike4c631292011-07-12 23:45:10 +10001025It's a built-in function that allocates memory, but unlike its namesakes
1026in some other languages it does not <em>initialize</em> the memory,
Rob Pike40747952012-03-25 11:34:51 +11001027it only <em>zeros</em> it.
Rob Pike4c631292011-07-12 23:45:10 +10001028That is,
1029<code>new(T)</code> allocates zeroed storage for a new item of type
Rob Pike2e5a1362009-09-27 17:59:36 -07001030<code>T</code> and returns its address, a value of type <code>*T</code>.
1031In Go terminology, it returns a pointer to a newly allocated zero value of type
1032<code>T</code>.
1033</p>
1034
1035<p>
Rob Piked1a3eda2011-08-21 09:46:19 +10001036Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange
1037when designing your data structures that the
1038zero value of each type can be used without further initialization. This means a user of
Rob Pike46f482a2011-05-25 06:44:09 +10001039the data structure can create one with <code>new</code> and get right to
Rob Pike2e5a1362009-09-27 17:59:36 -07001040work.
1041For example, the documentation for <code>bytes.Buffer</code> states that
1042"the zero value for <code>Buffer</code> is an empty buffer ready to use."
1043Similarly, <code>sync.Mutex</code> does not
1044have an explicit constructor or <code>Init</code> method.
1045Instead, the zero value for a <code>sync.Mutex</code>
1046is defined to be an unlocked mutex.
1047</p>
1048
1049<p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001050The zero-value-is-useful property works transitively. Consider this type declaration.
Rob Pike2e5a1362009-09-27 17:59:36 -07001051</p>
1052
1053<pre>
1054type SyncedBuffer struct {
Rob Pike163ecda2009-12-16 12:31:18 +11001055 lock sync.Mutex
1056 buffer bytes.Buffer
Rob Pike2e5a1362009-09-27 17:59:36 -07001057}
1058</pre>
1059
1060<p>
1061Values of type <code>SyncedBuffer</code> are also ready to use immediately upon allocation
Rob Pike9e2fbe12011-03-09 16:47:40 -08001062or just declaration. In the next snippet, both <code>p</code> and <code>v</code> will work
Rob Pikeb95048f2009-10-13 14:32:21 -07001063correctly without further arrangement.
Rob Pike2e5a1362009-09-27 17:59:36 -07001064</p>
1065
1066<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001067p := new(SyncedBuffer) // type *SyncedBuffer
1068var v SyncedBuffer // type SyncedBuffer
Rob Pike2e5a1362009-09-27 17:59:36 -07001069</pre>
1070
1071<h3 id="composite_literals">Constructors and composite literals</h3>
1072
1073<p>
1074Sometimes the zero value isn't good enough and an initializing
1075constructor is necessary, as in this example derived from
Rob Pikeb95048f2009-10-13 14:32:21 -07001076package <code>os</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -07001077</p>
1078
1079<pre>
1080func NewFile(fd int, name string) *File {
Rob Pike163ecda2009-12-16 12:31:18 +11001081 if fd &lt; 0 {
1082 return nil
1083 }
1084 f := new(File)
1085 f.fd = fd
1086 f.name = name
1087 f.dirinfo = nil
1088 f.nepipe = 0
1089 return f
Rob Pike2e5a1362009-09-27 17:59:36 -07001090}
1091</pre>
1092
1093<p>
Rob Pike430d4622009-10-20 12:30:39 -07001094There's a lot of boiler plate in there. We can simplify it
Rob Pike2e5a1362009-09-27 17:59:36 -07001095using a <i>composite literal</i>, which is
1096an expression that creates a
1097new instance each time it is evaluated.
1098</p>
1099
Rob Pike2e5a1362009-09-27 17:59:36 -07001100<pre>
1101func NewFile(fd int, name string) *File {
Rob Pike163ecda2009-12-16 12:31:18 +11001102 if fd &lt; 0 {
1103 return nil
1104 }
1105 f := File{fd, name, nil, 0}
1106 return &amp;f
Rob Pike2e5a1362009-09-27 17:59:36 -07001107}
1108</pre>
1109
1110<p>
Rob Pike9e2fbe12011-03-09 16:47:40 -08001111Note that, unlike in C, it's perfectly OK to return the address of a local variable;
Rob Pike2e5a1362009-09-27 17:59:36 -07001112the storage associated with the variable survives after the function
1113returns.
Rob Pike3e740792009-10-05 14:48:57 -07001114In fact, taking the address of a composite literal
1115allocates a fresh instance each time it is evaluated,
Rob Pikeb95048f2009-10-13 14:32:21 -07001116so we can combine these last two lines.
Rob Pike2e5a1362009-09-27 17:59:36 -07001117</p>
1118
1119<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001120 return &amp;File{fd, name, nil, 0}
Rob Pike2e5a1362009-09-27 17:59:36 -07001121</pre>
1122
1123<p>
1124The fields of a composite literal are laid out in order and must all be present.
1125However, by labeling the elements explicitly as <i>field</i><code>:</code><i>value</i>
1126pairs, the initializers can appear in any
1127order, with the missing ones left as their respective zero values. Thus we could say
1128</p>
1129
1130<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001131 return &amp;File{fd: fd, name: name}
Rob Pike2e5a1362009-09-27 17:59:36 -07001132</pre>
1133
1134<p>
1135As a limiting case, if a composite literal contains no fields at all, it creates
Russ Cox24ce19c2009-11-08 01:07:53 -08001136a zero value for the type. The expressions <code>new(File)</code> and <code>&amp;File{}</code> are equivalent.
Rob Pike2e5a1362009-09-27 17:59:36 -07001137</p>
1138
Rob Pike2e5a1362009-09-27 17:59:36 -07001139<p>
1140Composite literals can also be created for arrays, slices, and maps,
1141with the field labels being indices or map keys as appropriate.
Russ Cox24ce19c2009-11-08 01:07:53 -08001142In these examples, the initializations work regardless of the values of <code>Enone</code>,
Rob Pikeb95048f2009-10-13 14:32:21 -07001143<code>Eio</code>, and <code>Einval</code>, as long as they are distinct.
Rob Pike2e5a1362009-09-27 17:59:36 -07001144</p>
1145
1146<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001147a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
1148s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
1149m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
Rob Pike2e5a1362009-09-27 17:59:36 -07001150</pre>
1151
Rob Pike46f482a2011-05-25 06:44:09 +10001152<h3 id="allocation_make">Allocation with <code>make</code></h3>
Rob Pike2e5a1362009-09-27 17:59:36 -07001153
1154<p>
1155Back to allocation.
1156The built-in function <code>make(T, </code><i>args</i><code>)</code> serves
1157a purpose different from <code>new(T)</code>.
Rob Piked1a3eda2011-08-21 09:46:19 +10001158It creates slices, maps, and channels only, and it returns an <em>initialized</em>
1159(not <em>zeroed</em>)
1160value of type <code>T</code> (not <code>*T</code>).
Rob Pike2e5a1362009-09-27 17:59:36 -07001161The reason for the distinction
1162is that these three types are, under the covers, references to data structures that
1163must be initialized before use.
1164A slice, for example, is a three-item descriptor
1165containing a pointer to the data (inside an array), the length, and the
Rob Pike9e2fbe12011-03-09 16:47:40 -08001166capacity, and until those items are initialized, the slice is <code>nil</code>.
Robert Griesemer53440da2009-10-01 14:08:00 -07001167For slices, maps, and channels,
Rob Pike2e5a1362009-09-27 17:59:36 -07001168<code>make</code> initializes the internal data structure and prepares
1169the value for use.
1170For instance,
1171</p>
1172
1173<pre>
1174make([]int, 10, 100)
1175</pre>
1176
1177<p>
1178allocates an array of 100 ints and then creates a slice
1179structure with length 10 and a capacity of 100 pointing at the first
118010 elements of the array.
1181(When making a slice, the capacity can be omitted; see the section on slices
1182for more information.)
1183In contrast, <code>new([]int)</code> returns a pointer to a newly allocated, zeroed slice
1184structure, that is, a pointer to a <code>nil</code> slice value.
Oling Cate93891f2012-09-18 08:50:24 -07001185</p>
Rob Pike2e5a1362009-09-27 17:59:36 -07001186
1187<p>
Rob Pike46f482a2011-05-25 06:44:09 +10001188These examples illustrate the difference between <code>new</code> and
1189<code>make</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -07001190</p>
1191
1192<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001193var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
Andrew Gerrand766c3ff2010-02-22 14:51:22 -08001194var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
Rob Pike2e5a1362009-09-27 17:59:36 -07001195
1196// Unnecessarily complex:
Rob Pike163ecda2009-12-16 12:31:18 +11001197var p *[]int = new([]int)
1198*p = make([]int, 100, 100)
Rob Pike2e5a1362009-09-27 17:59:36 -07001199
1200// Idiomatic:
Rob Pike163ecda2009-12-16 12:31:18 +11001201v := make([]int, 100)
Rob Pike2e5a1362009-09-27 17:59:36 -07001202</pre>
1203
1204<p>
Rob Pike46f482a2011-05-25 06:44:09 +10001205Remember that <code>make</code> applies only to maps, slices and channels
Russ Cox24ce19c2009-11-08 01:07:53 -08001206and does not return a pointer.
Rob Pike46f482a2011-05-25 06:44:09 +10001207To obtain an explicit pointer allocate with <code>new</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -07001208</p>
1209
1210<h3 id="arrays">Arrays</h3>
1211
1212<p>
1213Arrays are useful when planning the detailed layout of memory and sometimes
Russ Cox24ce19c2009-11-08 01:07:53 -08001214can help avoid allocation, but primarily
Rob Pike2e5a1362009-09-27 17:59:36 -07001215they are a building block for slices, the subject of the next section.
1216To lay the foundation for that topic, here are a few words about arrays.
1217</p>
1218
1219<p>
1220There are major differences between the ways arrays work in Go and C.
Rob Pikeb95048f2009-10-13 14:32:21 -07001221In Go,
Rob Pike2e5a1362009-09-27 17:59:36 -07001222</p>
1223<ul>
1224<li>
1225Arrays are values. Assigning one array to another copies all the elements.
1226</li>
1227<li>
1228In particular, if you pass an array to a function, it
1229will receive a <i>copy</i> of the array, not a pointer to it.
1230<li>
1231The size of an array is part of its type. The types <code>[10]int</code>
1232and <code>[20]int</code> are distinct.
1233</li>
1234</ul>
1235
1236<p>
1237The value property can be useful but also expensive; if you want C-like behavior and efficiency,
Rob Pikeb95048f2009-10-13 14:32:21 -07001238you can pass a pointer to the array.
Rob Pike2e5a1362009-09-27 17:59:36 -07001239</p>
1240
1241<pre>
Rob Pike80e25fc2011-01-19 23:07:38 -05001242func Sum(a *[3]float64) (sum float64) {
Rob Pike163ecda2009-12-16 12:31:18 +11001243 for _, v := range *a {
1244 sum += v
1245 }
1246 return
Rob Pike2e5a1362009-09-27 17:59:36 -07001247}
1248
Rob Pike80e25fc2011-01-19 23:07:38 -05001249array := [...]float64{7.0, 8.5, 9.1}
Rob Pike163ecda2009-12-16 12:31:18 +11001250x := Sum(&amp;array) // Note the explicit address-of operator
Rob Pike2e5a1362009-09-27 17:59:36 -07001251</pre>
1252
1253<p>
1254But even this style isn't idiomatic Go. Slices are.
1255</p>
1256
1257<h3 id="slices">Slices</h3>
1258
1259<p>
Rob Pike3e740792009-10-05 14:48:57 -07001260Slices wrap arrays to give a more general, powerful, and convenient
1261interface to sequences of data. Except for items with explicit
1262dimension such as transformation matrices, most array programming in
1263Go is done with slices rather than simple arrays.
1264</p>
1265<p>
1266Slices are <i>reference types</i>, which means that if you assign one
1267slice to another, both refer to the same underlying array. For
1268instance, if a function takes a slice argument, changes it makes to
1269the elements of the slice will be visible to the caller, analogous to
1270passing a pointer to the underlying array. A <code>Read</code>
Russ Cox24ce19c2009-11-08 01:07:53 -08001271function can therefore accept a slice argument rather than a pointer
1272and a count; the length within the slice sets an upper
Rob Pike3e740792009-10-05 14:48:57 -07001273limit of how much data to read. Here is the signature of the
1274<code>Read</code> method of the <code>File</code> type in package
1275<code>os</code>:
1276</p>
1277<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04001278func (file *File) Read(buf []byte) (n int, err error)
Rob Pike3e740792009-10-05 14:48:57 -07001279</pre>
1280<p>
1281The method returns the number of bytes read and an error value, if
1282any. To read into the first 32 bytes of a larger buffer
Rob Pikeb95048f2009-10-13 14:32:21 -07001283<code>b</code>, <i>slice</i> (here used as a verb) the buffer.
Rob Pike3e740792009-10-05 14:48:57 -07001284</p>
1285<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001286 n, err := f.Read(buf[0:32])
Rob Pike3e740792009-10-05 14:48:57 -07001287</pre>
1288<p>
1289Such slicing is common and efficient. In fact, leaving efficiency aside for
Rob Pike40747952012-03-25 11:34:51 +11001290the moment, the following snippet would also read the first 32 bytes of the buffer.
Rob Pike3e740792009-10-05 14:48:57 -07001291</p>
1292<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001293 var n int
Rob Pike68050ac2011-11-01 21:50:21 -04001294 var err error
Rob Pike77f6f162009-12-25 07:13:14 +11001295 for i := 0; i &lt; 32; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11001296 nbytes, e := f.Read(buf[i:i+1]) // Read one byte.
1297 if nbytes == 0 || e != nil {
1298 err = e
1299 break
1300 }
1301 n += nbytes
1302 }
Rob Pike3e740792009-10-05 14:48:57 -07001303</pre>
1304<p>
1305The length of a slice may be changed as long as it still fits within
Rob Pikeb95048f2009-10-13 14:32:21 -07001306the limits of the underlying array; just assign it to a slice of
Rob Pike3e740792009-10-05 14:48:57 -07001307itself. The <i>capacity</i> of a slice, accessible by the built-in
1308function <code>cap</code>, reports the maximum length the slice may
1309assume. Here is a function to append data to a slice. If the data
1310exceeds the capacity, the slice is reallocated. The
1311resulting slice is returned. The function uses the fact that
1312<code>len</code> and <code>cap</code> are legal when applied to the
1313<code>nil</code> slice, and return 0.
1314</p>
1315<pre>
1316func Append(slice, data[]byte) []byte {
Rob Pike163ecda2009-12-16 12:31:18 +11001317 l := len(slice)
Rob Pike77f6f162009-12-25 07:13:14 +11001318 if l + len(data) &gt; cap(slice) { // reallocate
Rob Pike163ecda2009-12-16 12:31:18 +11001319 // Allocate double what's needed, for future growth.
1320 newSlice := make([]byte, (l+len(data))*2)
Ian Lance Taylorcd242fb2010-04-13 13:05:29 -07001321 // The copy function is predeclared and works for any slice type.
1322 copy(newSlice, slice)
Rob Pike163ecda2009-12-16 12:31:18 +11001323 slice = newSlice
1324 }
1325 slice = slice[0:l+len(data)]
1326 for i, c := range data {
1327 slice[l+i] = c
1328 }
1329 return slice
Rob Pike3e740792009-10-05 14:48:57 -07001330}
1331</pre>
1332<p>
1333We must return the slice afterwards because, although <code>Append</code>
1334can modify the elements of <code>slice</code>, the slice itself (the run-time data
1335structure holding the pointer, length, and capacity) is passed by value.
Oling Cate93891f2012-09-18 08:50:24 -07001336</p>
1337
Rob Pike0808b192010-11-01 21:46:04 -07001338<p>
1339The idea of appending to a slice is so useful it's captured by the
1340<code>append</code> built-in function. To understand that function's
1341design, though, we need a little more information, so we'll return
1342to it later.
Rob Pike2e5a1362009-09-27 17:59:36 -07001343</p>
1344
1345
1346<h3 id="maps">Maps</h3>
Rob Pike9dfe4042009-10-12 14:51:12 -07001347
1348<p>
1349Maps are a convenient and powerful built-in data structure to associate
1350values of different types.
Russ Cox24ce19c2009-11-08 01:07:53 -08001351The key can be of any type for which the equality operator is defined,
1352such as integers,
Rob Pike80e25fc2011-01-19 23:07:38 -05001353floating point and complex numbers,
Shenghou Ma0532f4d2012-03-21 09:33:55 -07001354strings, pointers, interfaces (as long as the dynamic type
1355supports equality), structs and arrays. Slices cannot be used as map keys,
1356because equality is not defined on them.
Rob Pike9dfe4042009-10-12 14:51:12 -07001357Like slices, maps are a reference type. If you pass a map to a function
1358that changes the contents of the map, the changes will be visible
1359in the caller.
1360</p>
1361<p>
1362Maps can be constructed using the usual composite literal syntax
1363with colon-separated key-value pairs,
1364so it's easy to build them during initialization.
1365</p>
1366<pre>
1367var timeZone = map[string] int {
Rob Pike163ecda2009-12-16 12:31:18 +11001368 "UTC": 0*60*60,
1369 "EST": -5*60*60,
1370 "CST": -6*60*60,
1371 "MST": -7*60*60,
1372 "PST": -8*60*60,
Rob Pike9dfe4042009-10-12 14:51:12 -07001373}
1374</pre>
1375<p>
1376Assigning and fetching map values looks syntactically just like
1377doing the same for arrays except that the index doesn't need to
Rob Pike47106422010-03-30 11:21:50 -07001378be an integer.
1379</p>
1380<pre>
1381offset := timeZone["EST"]
1382</pre>
1383<p>
1384An attempt to fetch a map value with a key that
1385is not present in the map will return the zero value for the type
1386of the entries
1387in the map. For instance, if the map contains integers, looking
1388up a non-existent key will return <code>0</code>.
Rob Pike9e2fbe12011-03-09 16:47:40 -08001389A set can be implemented as a map with value type <code>bool</code>.
1390Set the map entry to <code>true</code> to put the value in the set, and then
1391test it by simple indexing.
Rob Pike47106422010-03-30 11:21:50 -07001392</p>
Rob Pike9e2fbe12011-03-09 16:47:40 -08001393<pre>
1394attended := map[string] bool {
1395 "Ann": true,
1396 "Joe": true,
1397 ...
1398}
1399
1400if attended[person] { // will be false if person is not in the map
1401 fmt.Println(person, "was at the meeting")
1402}
1403</pre>
Rob Pike47106422010-03-30 11:21:50 -07001404<p>
1405Sometimes you need to distinguish a missing entry from
1406a zero value. Is there an entry for <code>"UTC"</code>
1407or is that zero value because it's not in the map at all?
1408You can discriminate with a form of multiple assignment.
Rob Pike9dfe4042009-10-12 14:51:12 -07001409</p>
1410<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001411var seconds int
1412var ok bool
Rob Pike9dfe4042009-10-12 14:51:12 -07001413seconds, ok = timeZone[tz]
1414</pre>
1415<p>
1416For obvious reasons this is called the &ldquo;comma ok&rdquo; idiom.
1417In this example, if <code>tz</code> is present, <code>seconds</code>
1418will be set appropriately and <code>ok</code> will be true; if not,
1419<code>seconds</code> will be set to zero and <code>ok</code> will
1420be false.
Rob Pike47106422010-03-30 11:21:50 -07001421Here's a function that puts it together with a nice error report:
Rob Pike9dfe4042009-10-12 14:51:12 -07001422</p>
1423<pre>
1424func offset(tz string) int {
Rob Pike163ecda2009-12-16 12:31:18 +11001425 if seconds, ok := timeZone[tz]; ok {
1426 return seconds
1427 }
Rob Pike9e2fbe12011-03-09 16:47:40 -08001428 log.Println("unknown time zone:", tz)
Rob Pike163ecda2009-12-16 12:31:18 +11001429 return 0
Rob Pike9dfe4042009-10-12 14:51:12 -07001430}
1431</pre>
1432<p>
1433To test for presence in the map without worrying about the actual value,
Rob Pike40747952012-03-25 11:34:51 +11001434you can use the blank identifier (<code>_</code>).
Rob Pike9dfe4042009-10-12 14:51:12 -07001435The blank identifier can be assigned or declared with any value of any type, with the
Rob Pike47106422010-03-30 11:21:50 -07001436value discarded harmlessly. For testing just presence in a map, use the blank
Rob Pike9dfe4042009-10-12 14:51:12 -07001437identifier in place of the usual variable for the value.
1438</p>
1439<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001440_, present := timeZone[tz]
Rob Pike9dfe4042009-10-12 14:51:12 -07001441</pre>
1442<p>
Rob Pike14efdea2012-02-12 09:11:44 +11001443To delete a map entry, use the <code>delete</code>
1444built-in function, whose arguments are the map and the key to be deleted.
1445It's safe to do this this even if the key is already absent
Rob Pike9dfe4042009-10-12 14:51:12 -07001446from the map.
1447</p>
1448<pre>
Rob Pike14efdea2012-02-12 09:11:44 +11001449delete(timeZone, "PDT") // Now on Standard Time
Rob Pike9dfe4042009-10-12 14:51:12 -07001450</pre>
Rob Pike47106422010-03-30 11:21:50 -07001451
Rob Pike2e5a1362009-09-27 17:59:36 -07001452<h3 id="printing">Printing</h3>
1453
Rob Pike9dfe4042009-10-12 14:51:12 -07001454<p>
1455Formatted printing in Go uses a style similar to C's <code>printf</code>
1456family but is richer and more general. The functions live in the <code>fmt</code>
1457package and have capitalized names: <code>fmt.Printf</code>, <code>fmt.Fprintf</code>,
1458<code>fmt.Sprintf</code> and so on. The string functions (<code>Sprintf</code> etc.)
1459return a string rather than filling in a provided buffer.
1460</p>
1461<p>
1462You don't need to provide a format string. For each of <code>Printf</code>,
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001463<code>Fprintf</code> and <code>Sprintf</code> there is another pair
Rob Pike9dfe4042009-10-12 14:51:12 -07001464of functions, for instance <code>Print</code> and <code>Println</code>.
1465These functions do not take a format string but instead generate a default
Rob Pike7ddbe792010-08-24 12:37:51 +10001466format for each argument. The <code>Println</code> versions also insert a blank
1467between arguments and append a newline to the output while
1468the <code>Print</code> versions add blanks only if the operand on neither side is a string.
Rob Pike9dfe4042009-10-12 14:51:12 -07001469In this example each line produces the same output.
1470</p>
1471<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001472fmt.Printf("Hello %d\n", 23)
1473fmt.Fprint(os.Stdout, "Hello ", 23, "\n")
Rob Pike7ddbe792010-08-24 12:37:51 +10001474fmt.Println("Hello", 23)
Rob Pike163ecda2009-12-16 12:31:18 +11001475fmt.Println(fmt.Sprint("Hello ", 23))
Rob Pike9dfe4042009-10-12 14:51:12 -07001476</pre>
1477<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001478As mentioned in
Shenghou Ma0532f4d2012-03-21 09:33:55 -07001479the <a href="http://tour.golang.org">Tour</a>, <code>fmt.Fprint</code>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001480and friends take as a first argument any object
Rob Pike9dfe4042009-10-12 14:51:12 -07001481that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code>
1482and <code>os.Stderr</code> are familiar instances.
1483</p>
1484<p>
1485Here things start to diverge from C. First, the numeric formats such as <code>%d</code>
1486do not take flags for signedness or size; instead, the printing routines use the
1487type of the argument to decide these properties.
1488</p>
1489<pre>
Rob Pike77f6f162009-12-25 07:13:14 +11001490var x uint64 = 1&lt;&lt;64 - 1
Rob Pike163ecda2009-12-16 12:31:18 +11001491fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))
Rob Pike9dfe4042009-10-12 14:51:12 -07001492</pre>
1493<p>
1494prints
1495</p>
1496<pre>
149718446744073709551615 ffffffffffffffff; -1 -1
1498</pre>
1499<p>
1500If you just want the default conversion, such as decimal for integers, you can use
1501the catchall format <code>%v</code> (for &ldquo;value&rdquo;); the result is exactly
1502what <code>Print</code> and <code>Println</code> would produce.
1503Moreover, that format can print <em>any</em> value, even arrays, structs, and
1504maps. Here is a print statement for the time zone map defined in the previous section.
1505</p>
1506<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001507fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001508</pre>
1509<p>
1510which gives output
1511</p>
1512<pre>
1513map[CST:-21600 PST:-28800 EST:-18000 UTC:0 MST:-25200]
1514</pre>
1515<p>
1516For maps the keys may be output in any order, of course.
1517When printing a struct, the modified format <code>%+v</code> annotates the
1518fields of the structure with their names, and for any value the alternate
1519format <code>%#v</code> prints the value in full Go syntax.
1520</p>
1521<pre>
1522type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +11001523 a int
Jeff R. Allenb7f44e972012-01-09 11:53:20 +11001524 b float64
Rob Pike163ecda2009-12-16 12:31:18 +11001525 c string
Rob Pike9dfe4042009-10-12 14:51:12 -07001526}
Rob Pike163ecda2009-12-16 12:31:18 +11001527t := &amp;T{ 7, -2.35, "abc\tdef" }
1528fmt.Printf("%v\n", t)
1529fmt.Printf("%+v\n", t)
1530fmt.Printf("%#v\n", t)
1531fmt.Printf("%#v\n", timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001532</pre>
1533<p>
1534prints
1535</p>
1536<pre>
1537&amp;{7 -2.35 abc def}
1538&amp;{a:7 b:-2.35 c:abc def}
1539&amp;main.T{a:7, b:-2.35, c:"abc\tdef"}
1540map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200}
1541</pre>
1542<p>
1543(Note the ampersands.)
1544That quoted string format is also available through <code>%q</code> when
1545applied to a value of type <code>string</code> or <code>[]byte</code>;
1546the alternate format <code>%#q</code> will use backquotes instead if possible.
1547Also, <code>%x</code> works on strings and arrays of bytes as well as on integers,
1548generating a long hexadecimal string, and with
1549a space in the format (<code>%&nbsp;x</code>) it puts spaces between the bytes.
1550</p>
1551<p>
1552Another handy format is <code>%T</code>, which prints the <em>type</em> of a value.
Oling Cate93891f2012-09-18 08:50:24 -07001553</p>
Rob Pike9dfe4042009-10-12 14:51:12 -07001554<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001555fmt.Printf(&quot;%T\n&quot;, timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001556</pre>
1557<p>
1558prints
1559</p>
1560<pre>
1561map[string] int
1562</pre>
1563<p>
1564If you want to control the default format for a custom type, all that's required is to define
Rob Pike46f482a2011-05-25 06:44:09 +10001565a method with the signature <code>String() string</code> on the type.
Rob Pikeb95048f2009-10-13 14:32:21 -07001566For our simple type <code>T</code>, that might look like this.
Rob Pike9dfe4042009-10-12 14:51:12 -07001567</p>
1568<pre>
1569func (t *T) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001570 return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
Rob Pike9dfe4042009-10-12 14:51:12 -07001571}
Rob Pike163ecda2009-12-16 12:31:18 +11001572fmt.Printf("%v\n", t)
Rob Pike9dfe4042009-10-12 14:51:12 -07001573</pre>
1574<p>
1575to print in the format
1576</p>
1577<pre>
15787/-2.35/"abc\tdef"
1579</pre>
1580<p>
Rob Pike89c59bc2011-05-11 08:31:24 -07001581(If you need to print <em>values</em> of type <code>T</code> as well as pointers to <code>T</code>,
1582the receiver for <code>String</code> must be of value type; this example used a pointer because
1583that's more efficient and idiomatic for struct types.
1584See the section below on <a href="#pointers_vs_values">pointers vs. value receivers</a> for more information.)
1585</p>
1586<p>
Rob Pike46f482a2011-05-25 06:44:09 +10001587Our <code>String</code> method is able to call <code>Sprintf</code> because the
Rob Pike9dfe4042009-10-12 14:51:12 -07001588print routines are fully reentrant and can be used recursively.
1589We can even go one step further and pass a print routine's arguments directly to another such routine.
Rob Pike6c088592010-06-14 22:40:35 -07001590The signature of <code>Printf</code> uses the type <code>...interface{}</code>
1591for its final argument to specify that an arbitrary number of parameters (of arbitrary type)
1592can appear after the format.
Rob Pike9dfe4042009-10-12 14:51:12 -07001593</p>
1594<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04001595func Printf(format string, v ...interface{}) (n int, err error) {
Rob Pike9dfe4042009-10-12 14:51:12 -07001596</pre>
1597<p>
Rob Pike6c088592010-06-14 22:40:35 -07001598Within the function <code>Printf</code>, <code>v</code> acts like a variable of type
1599<code>[]interface{}</code> but if it is passed to another variadic function, it acts like
1600a regular list of arguments.
1601Here is the implementation of the
Rob Pikee787f8272010-10-12 16:56:50 -07001602function <code>log.Println</code> we used above. It passes its arguments directly to
Rob Pike9dfe4042009-10-12 14:51:12 -07001603<code>fmt.Sprintln</code> for the actual formatting.
1604</p>
1605<pre>
Rob Pikee787f8272010-10-12 16:56:50 -07001606// Println prints to the standard logger in the manner of fmt.Println.
1607func Println(v ...interface{}) {
1608 std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string)
Rob Pike9dfe4042009-10-12 14:51:12 -07001609}
1610</pre>
1611<p>
Rob Pike70d0b6b22010-11-03 11:09:43 -07001612We write <code>...</code> after <code>v</code> in the nested call to <code>Sprintln</code> to tell the
Rob Pike0808b192010-11-01 21:46:04 -07001613compiler to treat <code>v</code> as a list of arguments; otherwise it would just pass
1614<code>v</code> as a single slice argument.
Oling Cate93891f2012-09-18 08:50:24 -07001615</p>
Rob Pike0808b192010-11-01 21:46:04 -07001616<p>
Rob Pike9dfe4042009-10-12 14:51:12 -07001617There's even more to printing than we've covered here. See the <code>godoc</code> documentation
1618for package <code>fmt</code> for the details.
1619</p>
Rob Pike6c088592010-06-14 22:40:35 -07001620<p>
1621By the way, a <code>...</code> parameter can be of a specific type, for instance <code>...int</code>
1622for a min function that chooses the least of a list of integers:
1623</p>
1624<pre>
1625func Min(a ...int) int {
1626 min := int(^uint(0) >> 1) // largest int
1627 for _, i := range a {
Robert Griesemer76f32282011-02-04 08:43:21 -08001628 if i &lt; min {
Rob Pike050905b2010-06-16 13:47:36 -07001629 min = i
1630 }
Rob Pike6c088592010-06-14 22:40:35 -07001631 }
1632 return min
1633}
1634</pre>
Rob Pike9dfe4042009-10-12 14:51:12 -07001635
Rob Pike0808b192010-11-01 21:46:04 -07001636<h3 id="append">Append</h3>
1637<p>
1638Now we have the missing piece we needed to explain the design of
1639the <code>append</code> built-in function. The signature of <code>append</code>
1640is different from our custom <code>Append</code> function above.
1641Schematically, it's like this:
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001642</p>
Rob Pike0808b192010-11-01 21:46:04 -07001643<pre>
1644func append(slice []<i>T</i>, elements...T) []<i>T</i>
1645</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001646<p>
Rob Pike0808b192010-11-01 21:46:04 -07001647where <i>T</i> is a placeholder for any given type. You can't
1648actually write a function in Go where the type <code>T</code>
1649is determined by the caller.
1650That's why <code>append</code> is built in: it needs support from the
1651compiler.
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001652</p>
Rob Pike0808b192010-11-01 21:46:04 -07001653<p>
1654What <code>append</code> does is append the elements to the end of
1655the slice and return the result. The result needs to be returned
1656because, as with our hand-written <code>Append</code>, the underlying
1657array may change. This simple example
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001658</p>
Rob Pike0808b192010-11-01 21:46:04 -07001659<pre>
1660x := []int{1,2,3}
1661x = append(x, 4, 5, 6)
1662fmt.Println(x)
1663</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001664<p>
Rob Pike0808b192010-11-01 21:46:04 -07001665prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a
1666little like <code>Printf</code>, collecting an arbitrary number of
1667arguments.
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001668</p>
Rob Pike0808b192010-11-01 21:46:04 -07001669<p>
1670But what if we wanted to do what our <code>Append</code> does and
1671append a slice to a slice? Easy: use <code>...</code> at the call
1672site, just as we did in the call to <code>Output</code> above. This
1673snippet produces identical output to the one above.
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001674</p>
Rob Pike0808b192010-11-01 21:46:04 -07001675<pre>
1676x := []int{1,2,3}
1677y := []int{4,5,6}
1678x = append(x, y...)
1679fmt.Println(x)
1680</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001681<p>
Rob Pike0808b192010-11-01 21:46:04 -07001682Without that <code>...</code>, it wouldn't compile because the types
1683would be wrong; <code>y</code> is not of type <code>int</code>.
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001684</p>
Rob Pike0808b192010-11-01 21:46:04 -07001685
Rob Pike6f89f3f2009-10-20 17:32:16 -07001686<h2 id="initialization">Initialization</h2>
1687
1688<p>
1689Although it doesn't look superficially very different from
1690initialization in C or C++, initialization in Go is more powerful.
1691Complex structures can be built during initialization and the ordering
1692issues between initialized objects in different packages are handled
1693correctly.
1694</p>
1695
1696<h3 id="constants">Constants</h3>
1697
1698<p>
1699Constants in Go are just that&mdash;constant.
1700They are created at compile time, even when defined as
1701locals in functions,
1702and can only be numbers, strings or booleans.
1703Because of the compile-time restriction, the expressions
1704that define them must be constant expressions,
1705evaluatable by the compiler. For instance,
1706<code>1&lt;&lt;3</code> is a constant expression, while
1707<code>math.Sin(math.Pi/4)</code> is not because
1708the function call to <code>math.Sin</code> needs
1709to happen at run time.
1710</p>
1711
1712<p>
1713In Go, enumerated constants are created using the <code>iota</code>
1714enumerator. Since <code>iota</code> can be part of an expression and
1715expressions can be implicitly repeated, it is easy to build intricate
1716sets of values.
Rob Pikebb3e3092009-10-31 18:29:06 -07001717</p>
Russ Coxa40065a2012-03-08 08:39:20 -05001718{{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}}
Rob Pike6f89f3f2009-10-20 17:32:16 -07001719<p>
1720The ability to attach a method such as <code>String</code> to a
1721type makes it possible for such values to format themselves
1722automatically for printing, even as part of a general type.
1723</p>
Russ Coxa40065a2012-03-08 08:39:20 -05001724{{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}}
Rob Pike6f89f3f2009-10-20 17:32:16 -07001725<p>
1726The expression <code>YB</code> prints as <code>1.00YB</code>,
Rob Pike49a35a62010-01-15 11:59:53 +11001727while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
Rob Pike6f89f3f2009-10-20 17:32:16 -07001728</p>
1729
Rob Pike40747952012-03-25 11:34:51 +11001730<p>
1731Note that it's fine to call <code>Sprintf</code> and friends in the
1732implementation of <code>String</code> methods, but beware of
1733recurring into the <code>String</code> method through the nested
1734<code>Sprintf</code> call using a string format
1735(<code>%s</code>, <code>%q</code>, <code>%v</code>, <code>%x</code> or <code>%X</code>).
1736The <code>ByteSize</code> implementation of <code>String</code> is safe
1737because it calls <code>Sprintf</code> with <code>%f</code>.
1738</p>
1739
Rob Pike6f89f3f2009-10-20 17:32:16 -07001740<h3 id="variables">Variables</h3>
1741
1742<p>
1743Variables can be initialized just like constants but the
1744initializer can be a general expression computed at run time.
1745</p>
1746<pre>
1747var (
Rob Pike163ecda2009-12-16 12:31:18 +11001748 HOME = os.Getenv("HOME")
1749 USER = os.Getenv("USER")
1750 GOROOT = os.Getenv("GOROOT")
Rob Pike6f89f3f2009-10-20 17:32:16 -07001751)
1752</pre>
1753
1754<h3 id="init">The init function</h3>
1755
1756<p>
Rob Pike46f482a2011-05-25 06:44:09 +10001757Finally, each source file can define its own niladic <code>init</code> function to
1758set up whatever state is required. (Actually each file can have multiple
Russ Coxe8d18522012-03-07 11:38:39 -05001759<code>init</code> functions.)
Rob Pike46f482a2011-05-25 06:44:09 +10001760And finally means finally: <code>init</code> is called after all the
Rob Pike6f89f3f2009-10-20 17:32:16 -07001761variable declarations in the package have evaluated their initializers,
1762and those are evaluated only after all the imported packages have been
1763initialized.
1764</p>
1765<p>
1766Besides initializations that cannot be expressed as declarations,
Rob Pike46f482a2011-05-25 06:44:09 +10001767a common use of <code>init</code> functions is to verify or repair
Rob Pike6f89f3f2009-10-20 17:32:16 -07001768correctness of the program state before real execution begins.
1769</p>
1770
1771<pre>
1772func init() {
Rob Pike163ecda2009-12-16 12:31:18 +11001773 if USER == "" {
Rob Pikeeea18d92011-02-01 12:47:35 -08001774 log.Fatal("$USER not set")
Rob Pike163ecda2009-12-16 12:31:18 +11001775 }
1776 if HOME == "" {
Rob Pike0cd0c3e82012-09-23 10:44:56 +10001777 HOME = "/home/" + USER
Rob Pike163ecda2009-12-16 12:31:18 +11001778 }
1779 if GOROOT == "" {
1780 GOROOT = HOME + "/go"
1781 }
1782 // GOROOT may be overridden by --goroot flag on command line.
1783 flag.StringVar(&amp;GOROOT, "goroot", GOROOT, "Go root directory")
Rob Pike6f89f3f2009-10-20 17:32:16 -07001784}
1785</pre>
1786
1787<h2 id="methods">Methods</h2>
Rob Pike2e5a1362009-09-27 17:59:36 -07001788
Rob Pike3e740792009-10-05 14:48:57 -07001789<h3 id="pointers_vs_values">Pointers vs. Values</h3>
1790<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001791Methods can be defined for any named type that is not a pointer or an interface;
Rob Pike3e740792009-10-05 14:48:57 -07001792the receiver does not have to be a struct.
Oling Cate93891f2012-09-18 08:50:24 -07001793</p>
Rob Pike3e740792009-10-05 14:48:57 -07001794<p>
1795In the discussion of slices above, we wrote an <code>Append</code>
1796function. We can define it as a method on slices instead. To do
1797this, we first declare a named type to which we can bind the method, and
1798then make the receiver for the method a value of that type.
1799</p>
1800<pre>
1801type ByteSlice []byte
1802
Rob Pikebcb46c82009-11-16 21:56:38 -08001803func (slice ByteSlice) Append(data []byte) []byte {
Rob Pike163ecda2009-12-16 12:31:18 +11001804 // Body exactly the same as above
Rob Pike3e740792009-10-05 14:48:57 -07001805}
1806</pre>
1807<p>
1808This still requires the method to return the updated slice. We can
1809eliminate that clumsiness by redefining the method to take a
1810<i>pointer</i> to a <code>ByteSlice</code> as its receiver, so the
1811method can overwrite the caller's slice.
1812</p>
1813<pre>
1814func (p *ByteSlice) Append(data []byte) {
Rob Pike163ecda2009-12-16 12:31:18 +11001815 slice := *p
1816 // Body as above, without the return.
1817 *p = slice
Rob Pike3e740792009-10-05 14:48:57 -07001818}
1819</pre>
1820<p>
1821In fact, we can do even better. If we modify our function so it looks
1822like a standard <code>Write</code> method, like this,
1823</p>
1824<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04001825func (p *ByteSlice) Write(data []byte) (n int, err error) {
Rob Pike163ecda2009-12-16 12:31:18 +11001826 slice := *p
1827 // Again as above.
1828 *p = slice
1829 return len(data), nil
Rob Pike3e740792009-10-05 14:48:57 -07001830}
1831</pre>
1832<p>
1833then the type <code>*ByteSlice</code> satisfies the standard interface
1834<code>io.Writer</code>, which is handy. For instance, we can
Rob Pikeb95048f2009-10-13 14:32:21 -07001835print into one.
Rob Pike3e740792009-10-05 14:48:57 -07001836</p>
1837<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001838 var b ByteSlice
1839 fmt.Fprintf(&amp;b, "This hour has %d days\n", 7)
Rob Pike3e740792009-10-05 14:48:57 -07001840</pre>
1841<p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001842We pass the address of a <code>ByteSlice</code>
Rob Pike3e740792009-10-05 14:48:57 -07001843because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>.
1844The rule about pointers vs. values for receivers is that value methods
1845can be invoked on pointers and values, but pointer methods can only be
1846invoked on pointers. This is because pointer methods can modify the
1847receiver; invoking them on a copy of the value would cause those
1848modifications to be discarded.
1849</p>
1850<p>
1851By the way, the idea of using <code>Write</code> on a slice of bytes
1852is implemented by <code>bytes.Buffer</code>.
1853</p>
Rob Pike2e5a1362009-09-27 17:59:36 -07001854
Rob Pike2119b362009-10-14 23:03:08 -07001855<h2 id="interfaces_and_types">Interfaces and other types</h2>
Rob Pike8aec6122009-09-02 16:41:41 -07001856
Rob Pikeb95048f2009-10-13 14:32:21 -07001857<h3 id="interfaces">Interfaces</h3>
1858<p>
1859Interfaces in Go provide a way to specify the behavior of an
1860object: if something can do <em>this</em>, then it can be used
1861<em>here</em>. We've seen a couple of simple examples already;
1862custom printers can be implemented by a <code>String</code> method
1863while <code>Fprintf</code> can generate output to anything
1864with a <code>Write</code> method.
Rob Pike2119b362009-10-14 23:03:08 -07001865Interfaces with only one or two methods are common in Go code, and are
Rob Pikeb95048f2009-10-13 14:32:21 -07001866usually given a name derived from the method, such as <code>io.Writer</code>
1867for something that implements <code>Write</code>.
1868</p>
1869<p>
1870A type can implement multiple interfaces.
1871For instance, a collection can be sorted
1872by the routines in package <code>sort</code> if it implements
1873<code>sort.Interface</code>, which contains <code>Len()</code>,
Russ Cox24ce19c2009-11-08 01:07:53 -08001874<code>Less(i, j int) bool</code>, and <code>Swap(i, j int)</code>,
Rob Pikeb95048f2009-10-13 14:32:21 -07001875and it could also have a custom formatter.
1876In this contrived example <code>Sequence</code> satisfies both.
1877</p>
Russ Coxa40065a2012-03-08 08:39:20 -05001878{{code "/doc/progs/eff_sequence.go" `/^type/` "$"}}
Russ Cox94439982009-06-25 09:38:35 -07001879
Rob Pikeb95048f2009-10-13 14:32:21 -07001880<h3 id="conversions">Conversions</h3>
1881
1882<p>
1883The <code>String</code> method of <code>Sequence</code> is recreating the
1884work that <code>Sprint</code> already does for slices. We can share the
1885effort if we convert the <code>Sequence</code> to a plain
1886<code>[]int</code> before calling <code>Sprint</code>.
1887</p>
1888<pre>
1889func (s Sequence) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001890 sort.Sort(s)
1891 return fmt.Sprint([]int(s))
Rob Pikeb95048f2009-10-13 14:32:21 -07001892}
1893</pre>
1894<p>
1895The conversion causes <code>s</code> to be treated as an ordinary slice
1896and therefore receive the default formatting.
1897Without the conversion, <code>Sprint</code> would find the
1898<code>String</code> method of <code>Sequence</code> and recur indefinitely.
1899Because the two types (<code>Sequence</code> and <code>[]int</code>)
1900are the same if we ignore the type name, it's legal to convert between them.
1901The conversion doesn't create a new value, it just temporarily acts
1902as though the existing value has a new type.
Rob Pike80e25fc2011-01-19 23:07:38 -05001903(There are other legal conversions, such as from integer to floating point, that
Rob Pikeb95048f2009-10-13 14:32:21 -07001904do create a new value.)
1905</p>
1906<p>
Rob Pikec2b64182009-11-01 20:54:11 -08001907It's an idiom in Go programs to convert the
Rob Pikeb95048f2009-10-13 14:32:21 -07001908type of an expression to access a different
1909set of methods. As an example, we could use the existing
Rob Pike029c9bc2011-10-06 10:46:18 -07001910type <code>sort.IntSlice</code> to reduce the entire example
Rob Pikeb95048f2009-10-13 14:32:21 -07001911to this:
1912</p>
1913<pre>
1914type Sequence []int
1915
1916// Method for printing - sorts the elements before printing
1917func (s Sequence) String() string {
Rob Pike029c9bc2011-10-06 10:46:18 -07001918 sort.IntSlice(s).Sort()
Rob Pike163ecda2009-12-16 12:31:18 +11001919 return fmt.Sprint([]int(s))
Rob Pikeb95048f2009-10-13 14:32:21 -07001920}
1921</pre>
1922<p>
1923Now, instead of having <code>Sequence</code> implement multiple
1924interfaces (sorting and printing), we're using the ability of a data item to be
Rob Pike029c9bc2011-10-06 10:46:18 -07001925converted to multiple types (<code>Sequence</code>, <code>sort.IntSlice</code>
Rob Pikeb95048f2009-10-13 14:32:21 -07001926and <code>[]int</code>), each of which does some part of the job.
1927That's more unusual in practice but can be effective.
1928</p>
1929
1930<h3 id="generality">Generality</h3>
Russ Cox94439982009-06-25 09:38:35 -07001931<p>
1932If a type exists only to implement an interface
1933and has no exported methods beyond that interface,
Rob Pike2119b362009-10-14 23:03:08 -07001934there is no need to export the type itself.
1935Exporting just the interface makes it clear that
1936it's the behavior that matters, not the implementation,
1937and that other implementations with different properties
1938can mirror the behavior of the original type.
Rob Pikeb95048f2009-10-13 14:32:21 -07001939It also avoids the need to repeat the documentation
1940on every instance of a common method.
Russ Cox94439982009-06-25 09:38:35 -07001941</p>
Russ Cox94439982009-06-25 09:38:35 -07001942<p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001943In such cases, the constructor should return an interface value
1944rather than the implementing type.
1945As an example, in the hash libraries
Rob Pike46f482a2011-05-25 06:44:09 +10001946both <code>crc32.NewIEEE</code> and <code>adler32.New</code>
Rob Pikeb95048f2009-10-13 14:32:21 -07001947return the interface type <code>hash.Hash32</code>.
Russ Cox94439982009-06-25 09:38:35 -07001948Substituting the CRC-32 algorithm for Adler-32 in a Go program
Rob Pikeb95048f2009-10-13 14:32:21 -07001949requires only changing the constructor call;
Rob Pikeeaf6a342009-07-06 15:15:56 -07001950the rest of the code is unaffected by the change of algorithm.
Russ Cox94439982009-06-25 09:38:35 -07001951</p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001952<p>
1953A similar approach allows the streaming cipher algorithms
Rob Pikea9aef262011-11-09 14:40:49 -08001954in the various <code>crypto</code> packages to be
Rob Pikeb95048f2009-10-13 14:32:21 -07001955separated from the block ciphers they chain together.
Rob Pikea9aef262011-11-09 14:40:49 -08001956The <code>Block</code> interface
Shenghou Ma0532f4d2012-03-21 09:33:55 -07001957in the <code>crypto/cipher</code> package specifies the
Rob Pikea9aef262011-11-09 14:40:49 -08001958behavior of a block cipher, which provides encryption
1959of a single block of data.
1960Then, by analogy with the <code>bufio</code> package,
1961cipher packages that implement this interface
1962can be used to construct streaming ciphers, represented
1963by the <code>Stream</code> interface, without
1964knowing the details of the block encryption.
Rob Pikeb95048f2009-10-13 14:32:21 -07001965</p>
1966<p>
Rob Pikea9aef262011-11-09 14:40:49 -08001967The <code>crypto/cipher</code> interfaces look like this:
Rob Pikeb95048f2009-10-13 14:32:21 -07001968</p>
1969<pre>
Rob Pikea9aef262011-11-09 14:40:49 -08001970type Block interface {
Rob Pike163ecda2009-12-16 12:31:18 +11001971 BlockSize() int
1972 Encrypt(src, dst []byte)
1973 Decrypt(src, dst []byte)
Rob Pikeb95048f2009-10-13 14:32:21 -07001974}
Russ Cox94439982009-06-25 09:38:35 -07001975
Rob Pikea9aef262011-11-09 14:40:49 -08001976type Stream interface {
1977 XORKeyStream(dst, src []byte)
1978}
1979</pre>
Russ Cox94439982009-06-25 09:38:35 -07001980
Rob Pikea9aef262011-11-09 14:40:49 -08001981<p>
1982Here's the definition of the counter mode (CTR) stream,
1983which turns a block cipher into a streaming cipher; notice
1984that the block cipher's details are abstracted away:
1985</p>
1986
1987<pre>
1988// NewCTR returns a Stream that encrypts/decrypts using the given Block in
1989// counter mode. The length of iv must be the same as the Block's block size.
1990func NewCTR(block Block, iv []byte) Stream
Rob Pikeb95048f2009-10-13 14:32:21 -07001991</pre>
1992<p>
Rob Pikea9aef262011-11-09 14:40:49 -08001993<code>NewCTR</code> applies not
Rob Pikeb95048f2009-10-13 14:32:21 -07001994just to one specific encryption algorithm and data source but to any
Rob Pikea9aef262011-11-09 14:40:49 -08001995implementation of the <code>Block</code> interface and any
1996<code>Stream</code>. Because they return
1997interface values, replacing CTR
1998encryption with other encryption modes is a localized change. The constructor
Russ Cox24ce19c2009-11-08 01:07:53 -08001999calls must be edited, but because the surrounding code must treat the result only
Rob Pikea9aef262011-11-09 14:40:49 -08002000as a <code>Stream</code>, it won't notice the difference.
Rob Pikeb95048f2009-10-13 14:32:21 -07002001</p>
Rob Piked2228692009-10-12 21:18:23 -07002002
Rob Pike2119b362009-10-14 23:03:08 -07002003<h3 id="interface_methods">Interfaces and methods</h3>
2004<p>
2005Since almost anything can have methods attached, almost anything can
2006satisfy an interface. One illustrative example is in the <code>http</code>
2007package, which defines the <code>Handler</code> interface. Any object
2008that implements <code>Handler</code> can serve HTTP requests.
2009</p>
2010<pre>
2011type Handler interface {
Rob Pike1edfb4c2010-09-29 11:12:52 -07002012 ServeHTTP(ResponseWriter, *Request)
Rob Pike2119b362009-10-14 23:03:08 -07002013}
2014</pre>
2015<p>
Rob Pike1edfb4c2010-09-29 11:12:52 -07002016<code>ResponseWriter</code> is itself an interface that provides access
2017to the methods needed to return the response to the client.
2018Those methods include the standard <code>Write</code> method, so an
2019<code>http.ResponseWriter</code> can be used wherever an <code>io.Writer</code>
2020can be used.
2021<code>Request</code> is a struct containing a parsed representation
2022of the request from the client.
Oling Cate93891f2012-09-18 08:50:24 -07002023</p>
Rob Pike1edfb4c2010-09-29 11:12:52 -07002024<p>
Rob Pike2119b362009-10-14 23:03:08 -07002025For brevity, let's ignore POSTs and assume HTTP requests are always
2026GETs; that simplification does not affect the way the handlers are
Rob Pike88407262009-10-16 11:13:40 -07002027set up. Here's a trivial but complete implementation of a handler to
Rob Pike2119b362009-10-14 23:03:08 -07002028count the number of times the
2029page is visited.
2030</p>
2031<pre>
2032// Simple counter server.
2033type Counter struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002034 n int
Rob Pike2119b362009-10-14 23:03:08 -07002035}
2036
Rob Pike1edfb4c2010-09-29 11:12:52 -07002037func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002038 ctr.n++
Rob Pike1edfb4c2010-09-29 11:12:52 -07002039 fmt.Fprintf(w, "counter = %d\n", ctr.n)
Rob Pike2119b362009-10-14 23:03:08 -07002040}
2041</pre>
2042<p>
Rob Pike1edfb4c2010-09-29 11:12:52 -07002043(Keeping with our theme, note how <code>Fprintf</code> can print to an
2044<code>http.ResponseWriter</code>.)
Rob Pike88407262009-10-16 11:13:40 -07002045For reference, here's how to attach such a server to a node on the URL tree.
Oling Cate93891f2012-09-18 08:50:24 -07002046</p>
Rob Pike2119b362009-10-14 23:03:08 -07002047<pre>
Rob Pike6ab6c492011-11-08 15:38:47 -08002048import "net/http"
Rob Pike2119b362009-10-14 23:03:08 -07002049...
Rob Pike163ecda2009-12-16 12:31:18 +11002050ctr := new(Counter)
2051http.Handle("/counter", ctr)
Rob Pike2119b362009-10-14 23:03:08 -07002052</pre>
2053<p>
2054But why make <code>Counter</code> a struct? An integer is all that's needed.
2055(The receiver needs to be a pointer so the increment is visible to the caller.)
2056</p>
2057<pre>
2058// Simpler counter server.
2059type Counter int
2060
Rob Pike1edfb4c2010-09-29 11:12:52 -07002061func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002062 *ctr++
Rob Pike1edfb4c2010-09-29 11:12:52 -07002063 fmt.Fprintf(w, "counter = %d\n", *ctr)
Rob Pike2119b362009-10-14 23:03:08 -07002064}
2065</pre>
2066<p>
2067What if your program has some internal state that needs to be notified that a page
2068has been visited? Tie a channel to the web page.
2069</p>
2070<pre>
2071// A channel that sends a notification on each visit.
2072// (Probably want the channel to be buffered.)
Rob Pike88407262009-10-16 11:13:40 -07002073type Chan chan *http.Request
Rob Pike2119b362009-10-14 23:03:08 -07002074
Rob Pike1edfb4c2010-09-29 11:12:52 -07002075func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike77f6f162009-12-25 07:13:14 +11002076 ch &lt;- req
Rob Pike1edfb4c2010-09-29 11:12:52 -07002077 fmt.Fprint(w, "notification sent")
Rob Pike2119b362009-10-14 23:03:08 -07002078}
2079</pre>
2080<p>
2081Finally, let's say we wanted to present on <code>/args</code> the arguments
2082used when invoking the server binary.
Rob Pike88407262009-10-16 11:13:40 -07002083It's easy to write a function to print the arguments.
Rob Pike2119b362009-10-14 23:03:08 -07002084</p>
2085<pre>
2086func ArgServer() {
Rob Piked1324d82011-11-24 08:51:47 -08002087 for _, s := range os.Args {
Rob Pike163ecda2009-12-16 12:31:18 +11002088 fmt.Println(s)
2089 }
Rob Pike2119b362009-10-14 23:03:08 -07002090}
2091</pre>
2092<p>
2093How do we turn that into an HTTP server? We could make <code>ArgServer</code>
2094a method of some type whose value we ignore, but there's a cleaner way.
Rob Pike88407262009-10-16 11:13:40 -07002095Since we can define a method for any type except pointers and interfaces,
2096we can write a method for a function.
Rob Pike2119b362009-10-14 23:03:08 -07002097The <code>http</code> package contains this code:
2098</p>
2099<pre>
2100// The HandlerFunc type is an adapter to allow the use of
2101// ordinary functions as HTTP handlers. If f is a function
2102// with the appropriate signature, HandlerFunc(f) is a
2103// Handler object that calls f.
Rob Pike1edfb4c2010-09-29 11:12:52 -07002104type HandlerFunc func(ResponseWriter, *Request)
Rob Pike2119b362009-10-14 23:03:08 -07002105
2106// ServeHTTP calls f(c, req).
Rob Pike1edfb4c2010-09-29 11:12:52 -07002107func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) {
2108 f(w, req)
Rob Pike2119b362009-10-14 23:03:08 -07002109}
2110</pre>
2111<p>
2112<code>HandlerFunc</code> is a type with a method, <code>ServeHTTP</code>,
2113so values of that type can serve HTTP requests. Look at the implementation
2114of the method: the receiver is a function, <code>f</code>, and the method
Rob Pikec2b64182009-11-01 20:54:11 -08002115calls <code>f</code>. That may seem odd but it's not that different from, say,
Rob Pike2119b362009-10-14 23:03:08 -07002116the receiver being a channel and the method sending on the channel.
2117</p>
2118<p>
Rob Pike88407262009-10-16 11:13:40 -07002119To make <code>ArgServer</code> into an HTTP server, we first modify it
2120to have the right signature.
Rob Pike2119b362009-10-14 23:03:08 -07002121</p>
2122<pre>
2123// Argument server.
Rob Pike1edfb4c2010-09-29 11:12:52 -07002124func ArgServer(w http.ResponseWriter, req *http.Request) {
Rob Piked1324d82011-11-24 08:51:47 -08002125 for _, s := range os.Args {
Rob Pike1edfb4c2010-09-29 11:12:52 -07002126 fmt.Fprintln(w, s)
Rob Pike163ecda2009-12-16 12:31:18 +11002127 }
Rob Pike2119b362009-10-14 23:03:08 -07002128}
2129</pre>
2130<p>
Rob Pike88407262009-10-16 11:13:40 -07002131<code>ArgServer</code> now has same signature as <code>HandlerFunc</code>,
2132so it can be converted to that type to access its methods,
Rob Pike029c9bc2011-10-06 10:46:18 -07002133just as we converted <code>Sequence</code> to <code>IntSlice</code>
2134to access <code>IntSlice.Sort</code>.
Rob Pike88407262009-10-16 11:13:40 -07002135The code to set it up is concise:
Rob Pike2119b362009-10-14 23:03:08 -07002136</p>
2137<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002138http.Handle("/args", http.HandlerFunc(ArgServer))
Rob Pike2119b362009-10-14 23:03:08 -07002139</pre>
2140<p>
2141When someone visits the page <code>/args</code>,
Rob Pike88407262009-10-16 11:13:40 -07002142the handler installed at that page has value <code>ArgServer</code>
2143and type <code>HandlerFunc</code>.
Rob Pike2119b362009-10-14 23:03:08 -07002144The HTTP server will invoke the method <code>ServeHTTP</code>
Rob Pike88407262009-10-16 11:13:40 -07002145of that type, with <code>ArgServer</code> as the receiver, which will in turn call
Rob Pike2119b362009-10-14 23:03:08 -07002146<code>ArgServer</code> (via the invocation <code>f(c, req)</code>
Rob Pike88407262009-10-16 11:13:40 -07002147inside <code>HandlerFunc.ServeHTTP</code>).
2148The arguments will then be displayed.
Rob Pike2119b362009-10-14 23:03:08 -07002149</p>
2150<p>
Rob Pike88407262009-10-16 11:13:40 -07002151In this section we have made an HTTP server from a struct, an integer,
Rob Pike2119b362009-10-14 23:03:08 -07002152a channel, and a function, all because interfaces are just sets of
2153methods, which can be defined for (almost) any type.
2154</p>
2155
Rob Pike88407262009-10-16 11:13:40 -07002156<h2 id="embedding">Embedding</h2>
2157
2158<p>
2159Go does not provide the typical, type-driven notion of subclassing,
2160but it does have the ability to &ldquo;borrow&rdquo; pieces of an
2161implementation by <em>embedding</em> types within a struct or
2162interface.
2163</p>
2164<p>
2165Interface embedding is very simple.
2166We've mentioned the <code>io.Reader</code> and <code>io.Writer</code> interfaces before;
2167here are their definitions.
2168</p>
2169<pre>
2170type Reader interface {
Rob Pike68050ac2011-11-01 21:50:21 -04002171 Read(p []byte) (n int, err error)
Rob Pike88407262009-10-16 11:13:40 -07002172}
2173
2174type Writer interface {
Rob Pike68050ac2011-11-01 21:50:21 -04002175 Write(p []byte) (n int, err error)
Rob Pike88407262009-10-16 11:13:40 -07002176}
2177</pre>
2178<p>
2179The <code>io</code> package also exports several other interfaces
2180that specify objects that can implement several such methods.
2181For instance, there is <code>io.ReadWriter</code>, an interface
2182containing both <code>Read</code> and <code>Write</code>.
2183We could specify <code>io.ReadWriter</code> by listing the
2184two methods explicitly, but it's easier and more evocative
2185to embed the two interfaces to form the new one, like this:
2186</p>
2187<pre>
Rob Pike7ddbe792010-08-24 12:37:51 +10002188// ReadWriter is the interface that combines the Reader and Writer interfaces.
Rob Pike88407262009-10-16 11:13:40 -07002189type ReadWriter interface {
Rob Pike163ecda2009-12-16 12:31:18 +11002190 Reader
2191 Writer
Rob Pike88407262009-10-16 11:13:40 -07002192}
2193</pre>
2194<p>
2195This says just what it looks like: A <code>ReadWriter</code> can do
2196what a <code>Reader</code> does <em>and</em> what a <code>Writer</code>
2197does; it is a union of the embedded interfaces (which must be disjoint
2198sets of methods).
2199Only interfaces can be embedded within interfaces.
Oling Cate93891f2012-09-18 08:50:24 -07002200</p>
Rob Pike88407262009-10-16 11:13:40 -07002201<p>
2202The same basic idea applies to structs, but with more far-reaching
2203implications. The <code>bufio</code> package has two struct types,
2204<code>bufio.Reader</code> and <code>bufio.Writer</code>, each of
2205which of course implements the analogous interfaces from package
2206<code>io</code>.
2207And <code>bufio</code> also implements a buffered reader/writer,
2208which it does by combining a reader and a writer into one struct
2209using embedding: it lists the types within the struct
2210but does not give them field names.
2211</p>
2212<pre>
2213// ReadWriter stores pointers to a Reader and a Writer.
2214// It implements io.ReadWriter.
2215type ReadWriter struct {
Rob Pike49a35a62010-01-15 11:59:53 +11002216 *Reader // *bufio.Reader
2217 *Writer // *bufio.Writer
Rob Pike88407262009-10-16 11:13:40 -07002218}
2219</pre>
2220<p>
Rob Pike49a35a62010-01-15 11:59:53 +11002221The embedded elements are pointers to structs and of course
2222must be initialized to point to valid structs before they
2223can be used.
2224The <code>ReadWriter</code> struct could be written as
Rob Pike88407262009-10-16 11:13:40 -07002225</p>
2226<pre>
2227type ReadWriter struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002228 reader *Reader
2229 writer *Writer
Rob Pike88407262009-10-16 11:13:40 -07002230}
2231</pre>
2232<p>
2233but then to promote the methods of the fields and to
2234satisfy the <code>io</code> interfaces, we would also need
2235to provide forwarding methods, like this:
2236</p>
2237<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04002238func (rw *ReadWriter) Read(p []byte) (n int, err error) {
Rob Pike163ecda2009-12-16 12:31:18 +11002239 return rw.reader.Read(p)
Rob Pike88407262009-10-16 11:13:40 -07002240}
2241</pre>
2242<p>
2243By embedding the structs directly, we avoid this bookkeeping.
2244The methods of embedded types come along for free, which means that <code>bufio.ReadWriter</code>
2245not only has the methods of <code>bufio.Reader</code> and <code>bufio.Writer</code>,
2246it also satisfies all three interfaces:
2247<code>io.Reader</code>,
2248<code>io.Writer</code>, and
2249<code>io.ReadWriter</code>.
2250</p>
2251<p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002252There's an important way in which embedding differs from subclassing. When we embed a type,
Rob Pikec58d9ef2009-10-16 11:23:45 -07002253the methods of that type become methods of the outer type,
2254but when they are invoked the receiver of the method is the inner type, not the outer one.
Rob Pike88407262009-10-16 11:13:40 -07002255In our example, when the <code>Read</code> method of a <code>bufio.ReadWriter</code> is
Rob Pikef00be0c2009-10-16 16:16:02 -07002256invoked, it has exactly the same effect as the forwarding method written out above;
Rob Pike88407262009-10-16 11:13:40 -07002257the receiver is the <code>reader</code> field of the <code>ReadWriter</code>, not the
2258<code>ReadWriter</code> itself.
2259</p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002260<p>
2261Embedding can also be a simple convenience.
2262This example shows an embedded field alongside a regular, named field.
2263</p>
2264<pre>
2265type Job struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002266 Command string
2267 *log.Logger
Rob Pikef00be0c2009-10-16 16:16:02 -07002268}
2269</pre>
2270<p>
2271The <code>Job</code> type now has the <code>Log</code>, <code>Logf</code>
2272and other
Rob Pike6c088592010-06-14 22:40:35 -07002273methods of <code>*log.Logger</code>. We could have given the <code>Logger</code>
Rob Pike49a35a62010-01-15 11:59:53 +11002274a field name, of course, but it's not necessary to do so. And now, once
2275initialized, we can
2276log to the <code>Job</code>:
Rob Pikef00be0c2009-10-16 16:16:02 -07002277</p>
2278<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002279job.Log("starting now...")
Rob Pikef00be0c2009-10-16 16:16:02 -07002280</pre>
2281<p>
Rob Pike9f60b032009-10-19 10:34:00 -07002282The <code>Logger</code> is a regular field of the struct and we can initialize
Rob Pike49a35a62010-01-15 11:59:53 +11002283it in the usual way with a constructor,
Rob Pike9f60b032009-10-19 10:34:00 -07002284</p>
2285<pre>
2286func NewJob(command string, logger *log.Logger) *Job {
Rob Pike163ecda2009-12-16 12:31:18 +11002287 return &amp;Job{command, logger}
Rob Pike9f60b032009-10-19 10:34:00 -07002288}
2289</pre>
2290<p>
Rob Pike49a35a62010-01-15 11:59:53 +11002291or with a composite literal,
2292</p>
2293<pre>
Rob Pikee787f8272010-10-12 16:56:50 -07002294job := &amp;Job{command, log.New(os.Stderr, "Job: ", log.Ldate)}
Rob Pike49a35a62010-01-15 11:59:53 +11002295</pre>
2296<p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002297If we need to refer to an embedded field directly, the type name of the field,
2298ignoring the package qualifier, serves as a field name. If we needed to access the
2299<code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>,
2300we would write <code>job.Logger</code>.
2301This would be useful if we wanted to refine the methods of <code>Logger</code>.
2302</p>
2303<pre>
Ben Lynn6be0bdf2011-06-21 10:55:07 +10002304func (job *Job) Logf(format string, args ...interface{}) {
Aaron Kempcb871ce2012-03-30 17:51:24 -07002305 job.Logger.Logf("%q: %s", job.Command, fmt.Sprintf(format, args...))
Rob Pikef00be0c2009-10-16 16:16:02 -07002306}
2307</pre>
2308<p>
2309Embedding types introduces the problem of name conflicts but the rules to resolve
2310them are simple.
2311First, a field or method <code>X</code> hides any other item <code>X</code> in a more deeply
2312nested part of the type.
2313If <code>log.Logger</code> contained a field or method called <code>Command</code>, the <code>Command</code> field
2314of <code>Job</code> would dominate it.
2315</p>
2316<p>
2317Second, if the same name appears at the same nesting level, it is usually an error;
Rob Pike6c088592010-06-14 22:40:35 -07002318it would be erroneous to embed <code>log.Logger</code> if the <code>Job</code> struct
Rob Pikef00be0c2009-10-16 16:16:02 -07002319contained another field or method called <code>Logger</code>.
2320However, if the duplicate name is never mentioned in the program outside the type definition, it is OK.
2321This qualification provides some protection against changes made to types embedded from outside; there
Rob Pikec2b64182009-11-01 20:54:11 -08002322is no problem if a field is added that conflicts with another field in another subtype if neither field
2323is ever used.
Rob Pikef00be0c2009-10-16 16:16:02 -07002324</p>
Rob Pike88407262009-10-16 11:13:40 -07002325
2326
Rob Pike430d4622009-10-20 12:30:39 -07002327<h2 id="concurrency">Concurrency</h2>
2328
2329<h3 id="sharing">Share by communicating</h3>
2330
2331<p>
Rob Pikebb3e3092009-10-31 18:29:06 -07002332Concurrent programming is a large topic and there is space only for some
2333Go-specific highlights here.
2334</p>
2335<p>
Rob Pike430d4622009-10-20 12:30:39 -07002336Concurrent programming in many environments is made difficult by the
2337subtleties required to implement correct access to shared variables. Go encourages
2338a different approach in which shared values are passed around on channels
2339and, in fact, never actively shared by separate threads of execution.
2340Only one goroutine has access to the value at any given time.
2341Data races cannot occur, by design.
2342To encourage this way of thinking we have reduced it to a slogan:
2343</p>
2344<blockquote>
2345Do not communicate by sharing memory;
2346instead, share memory by communicating.
2347</blockquote>
2348<p>
2349This approach can be taken too far. Reference counts may be best done
2350by putting a mutex around an integer variable, for instance. But as a
2351high-level approach, using channels to control access makes it easier
2352to write clear, correct programs.
2353</p>
2354<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002355One way to think about this model is to consider a typical single-threaded
Rob Pike430d4622009-10-20 12:30:39 -07002356program running on one CPU. It has no need for synchronization primitives.
2357Now run another such instance; it too needs no synchronization. Now let those
2358two communicate; if the communication is the synchronizer, there's still no need
Rob Pikec2b64182009-11-01 20:54:11 -08002359for other synchronization. Unix pipelines, for example, fit this model
Rob Pikebb3e3092009-10-31 18:29:06 -07002360perfectly. Although Go's approach to concurrency originates in Hoare's
Rob Pike430d4622009-10-20 12:30:39 -07002361Communicating Sequential Processes (CSP),
2362it can also be seen as a type-safe generalization of Unix pipes.
2363</p>
2364
2365<h3 id="goroutines">Goroutines</h3>
2366
Rob Pikebb3e3092009-10-31 18:29:06 -07002367<p>
2368They're called <em>goroutines</em> because the existing
2369terms&mdash;threads, coroutines, processes, and so on&mdash;convey
2370inaccurate connotations. A goroutine has a simple model: it is a
Shenghou Ma0532f4d2012-03-21 09:33:55 -07002371function executing concurrently with other goroutines in the same
Rob Pikebb3e3092009-10-31 18:29:06 -07002372address space. It is lightweight, costing little more than the
2373allocation of stack space.
2374And the stacks start small, so they are cheap, and grow
2375by allocating (and freeing) heap storage as required.
2376</p>
2377<p>
2378Goroutines are multiplexed onto multiple OS threads so if one should
2379block, such as while waiting for I/O, others continue to run. Their
2380design hides many of the complexities of thread creation and
2381management.
2382</p>
2383<p>
2384Prefix a function or method call with the <code>go</code>
2385keyword to run the call in a new goroutine.
2386When the call completes, the goroutine
2387exits, silently. (The effect is similar to the Unix shell's
2388<code>&amp;</code> notation for running a command in the
2389background.)
2390</p>
2391<pre>
Oling Cate93891f2012-09-18 08:50:24 -07002392go list.Sort() // run list.Sort concurrently; don't wait for it.
Rob Pikebb3e3092009-10-31 18:29:06 -07002393</pre>
2394<p>
2395A function literal can be handy in a goroutine invocation.
Oling Cate93891f2012-09-18 08:50:24 -07002396</p>
Rob Pikebb3e3092009-10-31 18:29:06 -07002397<pre>
David Symondse5cc09a2012-03-16 14:27:11 +11002398func Announce(message string, delay time.Duration) {
Rob Pike163ecda2009-12-16 12:31:18 +11002399 go func() {
2400 time.Sleep(delay)
2401 fmt.Println(message)
2402 }() // Note the parentheses - must call the function.
Rob Pikebb3e3092009-10-31 18:29:06 -07002403}
2404</pre>
2405<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002406In Go, function literals are closures: the implementation makes
Rob Pikebb3e3092009-10-31 18:29:06 -07002407sure the variables referred to by the function survive as long as they are active.
Oling Cate93891f2012-09-18 08:50:24 -07002408</p>
Rob Pikebb3e3092009-10-31 18:29:06 -07002409<p>
2410These examples aren't too practical because the functions have no way of signaling
2411completion. For that, we need channels.
2412</p>
2413
Rob Pike430d4622009-10-20 12:30:39 -07002414<h3 id="channels">Channels</h3>
2415
Rob Pikebb3e3092009-10-31 18:29:06 -07002416<p>
2417Like maps, channels are a reference type and are allocated with <code>make</code>.
2418If an optional integer parameter is provided, it sets the buffer size for the channel.
2419The default is zero, for an unbuffered or synchronous channel.
2420</p>
2421<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002422ci := make(chan int) // unbuffered channel of integers
2423cj := make(chan int, 0) // unbuffered channel of integers
2424cs := make(chan *os.File, 100) // buffered channel of pointers to Files
Rob Pikebb3e3092009-10-31 18:29:06 -07002425</pre>
2426<p>
2427Channels combine communication&mdash;the exchange of a value&mdash;with
2428synchronization&mdash;guaranteeing that two calculations (goroutines) are in
2429a known state.
2430</p>
2431<p>
2432There are lots of nice idioms using channels. Here's one to get us started.
2433In the previous section we launched a sort in the background. A channel
2434can allow the launching goroutine to wait for the sort to complete.
2435</p>
2436<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002437c := make(chan int) // Allocate a channel.
Rob Pikebb3e3092009-10-31 18:29:06 -07002438// Start the sort in a goroutine; when it completes, signal on the channel.
2439go func() {
Rob Pike163ecda2009-12-16 12:31:18 +11002440 list.Sort()
Oling Cate93891f2012-09-18 08:50:24 -07002441 c &lt;- 1 // Send a signal; value does not matter.
Rob Pike163ecda2009-12-16 12:31:18 +11002442}()
2443doSomethingForAWhile()
2444&lt;-c // Wait for sort to finish; discard sent value.
Rob Pikebb3e3092009-10-31 18:29:06 -07002445</pre>
2446<p>
2447Receivers always block until there is data to receive.
2448If the channel is unbuffered, the sender blocks until the receiver has
2449received the value.
2450If the channel has a buffer, the sender blocks only until the
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08002451value has been copied to the buffer; if the buffer is full, this
2452means waiting until some receiver has retrieved a value.
Rob Pikebb3e3092009-10-31 18:29:06 -07002453</p>
2454<p>
2455A buffered channel can be used like a semaphore, for instance to
2456limit throughput. In this example, incoming requests are passed
2457to <code>handle</code>, which sends a value into the channel, processes
Rob Pikec2b64182009-11-01 20:54:11 -08002458the request, and then receives a value from the channel.
Rob Pikebb3e3092009-10-31 18:29:06 -07002459The capacity of the channel buffer limits the number of
2460simultaneous calls to <code>process</code>.
2461</p>
2462<pre>
2463var sem = make(chan int, MaxOutstanding)
2464
2465func handle(r *Request) {
Rob Pike77f6f162009-12-25 07:13:14 +11002466 sem &lt;- 1 // Wait for active queue to drain.
Rob Pike163ecda2009-12-16 12:31:18 +11002467 process(r) // May take a long time.
Rob Pike77f6f162009-12-25 07:13:14 +11002468 &lt;-sem // Done; enable next request to run.
Rob Pikebb3e3092009-10-31 18:29:06 -07002469}
2470
2471func Serve(queue chan *Request) {
2472 for {
Rob Pike77f6f162009-12-25 07:13:14 +11002473 req := &lt;-queue
Rob Pike163ecda2009-12-16 12:31:18 +11002474 go handle(req) // Don't wait for handle to finish.
Rob Pikebb3e3092009-10-31 18:29:06 -07002475 }
2476}
2477</pre>
2478<p>
2479Here's the same idea implemented by starting a fixed
2480number of <code>handle</code> goroutines all reading from the request
2481channel.
2482The number of goroutines limits the number of simultaneous
2483calls to <code>process</code>.
2484This <code>Serve</code> function also accepts a channel on which
2485it will be told to exit; after launching the goroutines it blocks
2486receiving from that channel.
2487</p>
2488<pre>
2489func handle(queue chan *Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002490 for r := range queue {
2491 process(r)
2492 }
Rob Pikebb3e3092009-10-31 18:29:06 -07002493}
2494
Jongmin Kim08f919f2012-04-13 15:22:40 +10002495func Serve(clientRequests chan *Request, quit chan bool) {
Rob Pike163ecda2009-12-16 12:31:18 +11002496 // Start handlers
Rob Pike77f6f162009-12-25 07:13:14 +11002497 for i := 0; i &lt; MaxOutstanding; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11002498 go handle(clientRequests)
2499 }
Rob Pike77f6f162009-12-25 07:13:14 +11002500 &lt;-quit // Wait to be told to exit.
Rob Pikebb3e3092009-10-31 18:29:06 -07002501}
2502</pre>
2503
2504<h3 id="chan_of_chan">Channels of channels</h3>
2505<p>
2506One of the most important properties of Go is that
2507a channel is a first-class value that can be allocated and passed
2508around like any other. A common use of this property is
2509to implement safe, parallel demultiplexing.
Oling Cate93891f2012-09-18 08:50:24 -07002510</p>
Rob Pikebb3e3092009-10-31 18:29:06 -07002511<p>
2512In the example in the previous section, <code>handle</code> was
2513an idealized handler for a request but we didn't define the
2514type it was handling. If that type includes a channel on which
2515to reply, each client can provide its own path for the answer.
2516Here's a schematic definition of type <code>Request</code>.
2517</p>
2518<pre>
2519type Request struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002520 args []int
2521 f func([]int) int
2522 resultChan chan int
Rob Pikebb3e3092009-10-31 18:29:06 -07002523}
2524</pre>
2525<p>
2526The client provides a function and its arguments, as well as
2527a channel inside the request object on which to receive the answer.
2528</p>
2529<pre>
2530func sum(a []int) (s int) {
Rob Pike163ecda2009-12-16 12:31:18 +11002531 for _, v := range a {
2532 s += v
2533 }
2534 return
Rob Pikebb3e3092009-10-31 18:29:06 -07002535}
2536
2537request := &amp;Request{[]int{3, 4, 5}, sum, make(chan int)}
2538// Send request
Rob Pike77f6f162009-12-25 07:13:14 +11002539clientRequests &lt;- request
Rob Pikebb3e3092009-10-31 18:29:06 -07002540// Wait for response.
Rob Pike77f6f162009-12-25 07:13:14 +11002541fmt.Printf("answer: %d\n", &lt;-request.resultChan)
Rob Pikebb3e3092009-10-31 18:29:06 -07002542</pre>
2543<p>
2544On the server side, the handler function is the only thing that changes.
2545</p>
2546<pre>
2547func handle(queue chan *Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002548 for req := range queue {
Rob Pike77f6f162009-12-25 07:13:14 +11002549 req.resultChan &lt;- req.f(req.args)
Rob Pike163ecda2009-12-16 12:31:18 +11002550 }
Rob Pikebb3e3092009-10-31 18:29:06 -07002551}
2552</pre>
2553<p>
2554There's clearly a lot more to do to make it realistic, but this
2555code is a framework for a rate-limited, parallel, non-blocking RPC
2556system, and there's not a mutex in sight.
2557</p>
2558
2559<h3 id="parallel">Parallelization</h3>
2560<p>
2561Another application of these ideas is to parallelize a calculation
2562across multiple CPU cores. If the calculation can be broken into
Rob Pike40747952012-03-25 11:34:51 +11002563separate pieces that can execute independently, it can be parallelized,
2564with a channel to signal when each piece completes.
Rob Pikebb3e3092009-10-31 18:29:06 -07002565</p>
2566<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002567Let's say we have an expensive operation to perform on a vector of items,
Rob Pikebb3e3092009-10-31 18:29:06 -07002568and that the value of the operation on each item is independent,
2569as in this idealized example.
2570</p>
2571<pre>
Rob Pikec2b64182009-11-01 20:54:11 -08002572type Vector []float64
Rob Pikebb3e3092009-10-31 18:29:06 -07002573
Rob Pike617a6a52009-12-23 13:47:58 +11002574// Apply the operation to v[i], v[i+1] ... up to v[n-1].
Rob Pikec2b64182009-11-01 20:54:11 -08002575func (v Vector) DoSome(i, n int, u Vector, c chan int) {
Rob Pike77f6f162009-12-25 07:13:14 +11002576 for ; i &lt; n; i++ {
Rob Pikebb3e3092009-10-31 18:29:06 -07002577 v[i] += u.Op(v[i])
2578 }
Rob Pike77f6f162009-12-25 07:13:14 +11002579 c &lt;- 1 // signal that this piece is done
Rob Pikebb3e3092009-10-31 18:29:06 -07002580}
2581</pre>
2582<p>
2583We launch the pieces independently in a loop, one per CPU.
2584They can complete in any order but it doesn't matter; we just
2585count the completion signals by draining the channel after
2586launching all the goroutines.
2587</p>
2588<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002589const NCPU = 4 // number of CPU cores
Rob Pikebb3e3092009-10-31 18:29:06 -07002590
Rob Pikec2b64182009-11-01 20:54:11 -08002591func (v Vector) DoAll(u Vector) {
Rob Pike163ecda2009-12-16 12:31:18 +11002592 c := make(chan int, NCPU) // Buffering optional but sensible.
Rob Pike77f6f162009-12-25 07:13:14 +11002593 for i := 0; i &lt; NCPU; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11002594 go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c)
Rob Pikebb3e3092009-10-31 18:29:06 -07002595 }
2596 // Drain the channel.
Rob Pike77f6f162009-12-25 07:13:14 +11002597 for i := 0; i &lt; NCPU; i++ {
2598 &lt;-c // wait for one task to complete
Rob Pikebb3e3092009-10-31 18:29:06 -07002599 }
2600 // All done.
2601}
2602
2603</pre>
2604
Rob Pikedc3b4932009-11-15 13:09:43 -08002605<p>
Rob Pike40747952012-03-25 11:34:51 +11002606The current implementation of the Go runtime
Rob Pikedc3b4932009-11-15 13:09:43 -08002607will not parallelize this code by default.
2608It dedicates only a single core to user-level processing. An
2609arbitrary number of goroutines can be blocked in system calls, but
2610by default only one can be executing user-level code at any time.
2611It should be smarter and one day it will be smarter, but until it
2612is if you want CPU parallelism you must tell the run-time
2613how many goroutines you want executing code simultaneously. There
2614are two related ways to do this. Either run your job with environment
2615variable <code>GOMAXPROCS</code> set to the number of cores to use
Dmitriy Vyukova03c5192012-01-12 22:06:50 +04002616or import the <code>runtime</code> package and call
Rob Pikedc3b4932009-11-15 13:09:43 -08002617<code>runtime.GOMAXPROCS(NCPU)</code>.
Dmitriy Vyukova03c5192012-01-12 22:06:50 +04002618A helpful value might be <code>runtime.NumCPU()</code>, which reports the number
2619of logical CPUs on the local machine.
Rob Pikedc3b4932009-11-15 13:09:43 -08002620Again, this requirement is expected to be retired as the scheduling and run-time improve.
2621</p>
2622
Rob Pike430d4622009-10-20 12:30:39 -07002623<h3 id="leaky_buffer">A leaky buffer</h3>
2624
2625<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002626The tools of concurrent programming can even make non-concurrent
Rob Pike430d4622009-10-20 12:30:39 -07002627ideas easier to express. Here's an example abstracted from an RPC
2628package. The client goroutine loops receiving data from some source,
2629perhaps a network. To avoid allocating and freeing buffers, it keeps
2630a free list, and uses a buffered channel to represent it. If the
2631channel is empty, a new buffer gets allocated.
2632Once the message buffer is ready, it's sent to the server on
2633<code>serverChan</code>.
2634</p>
2635<pre>
Russ Cox24ce19c2009-11-08 01:07:53 -08002636var freeList = make(chan *Buffer, 100)
2637var serverChan = make(chan *Buffer)
Rob Pike430d4622009-10-20 12:30:39 -07002638
2639func client() {
Rob Pike163ecda2009-12-16 12:31:18 +11002640 for {
Rob Pike61978aa2011-01-31 12:46:38 -08002641 var b *Buffer
2642 // Grab a buffer if available; allocate if not.
2643 select {
2644 case b = &lt;-freeList:
2645 // Got one; nothing more to do.
2646 default:
2647 // None free, so allocate a new one.
Rob Pike163ecda2009-12-16 12:31:18 +11002648 b = new(Buffer)
2649 }
Rob Pike61978aa2011-01-31 12:46:38 -08002650 load(b) // Read next message from the net.
2651 serverChan &lt;- b // Send to server.
Rob Pike163ecda2009-12-16 12:31:18 +11002652 }
Rob Pike430d4622009-10-20 12:30:39 -07002653}
2654</pre>
2655<p>
Rob Pike61978aa2011-01-31 12:46:38 -08002656The server loop receives each message from the client, processes it,
Rob Pike430d4622009-10-20 12:30:39 -07002657and returns the buffer to the free list.
2658</p>
2659<pre>
2660func server() {
Rob Pike163ecda2009-12-16 12:31:18 +11002661 for {
Rob Pike61978aa2011-01-31 12:46:38 -08002662 b := &lt;-serverChan // Wait for work.
Rob Pike163ecda2009-12-16 12:31:18 +11002663 process(b)
Rob Pike61978aa2011-01-31 12:46:38 -08002664 // Reuse buffer if there's room.
2665 select {
2666 case freeList &lt;- b:
2667 // Buffer on free list; nothing more to do.
2668 default:
2669 // Free list full, just carry on.
2670 }
Rob Pike163ecda2009-12-16 12:31:18 +11002671 }
Rob Pike430d4622009-10-20 12:30:39 -07002672}
2673</pre>
2674<p>
Rob Pike61978aa2011-01-31 12:46:38 -08002675The client attempts to retrieve a buffer from <code>freeList</code>;
2676if none is available, it allocates a fresh one.
2677The server's send to <code>freeList</code> puts <code>b</code> back
Rob Pike430d4622009-10-20 12:30:39 -07002678on the free list unless the list is full, in which case the
2679buffer is dropped on the floor to be reclaimed by
2680the garbage collector.
Rob Pike61978aa2011-01-31 12:46:38 -08002681(The <code>default</code> clauses in the <code>select</code>
2682statements execute when no other case is ready,
2683meaning that the <code>selects</code> never block.)
Rob Pike430d4622009-10-20 12:30:39 -07002684This implementation builds a leaky bucket free list
2685in just a few lines, relying on the buffered channel and
2686the garbage collector for bookkeeping.
2687</p>
2688
Rob Piked2228692009-10-12 21:18:23 -07002689<h2 id="errors">Errors</h2>
2690
2691<p>
2692Library routines must often return some sort of error indication to
2693the caller. As mentioned earlier, Go's multivalue return makes it
2694easy to return a detailed error description alongside the normal
Rob Pike68050ac2011-11-01 21:50:21 -04002695return value. By convention, errors have type <code>error</code>,
2696a simple built-in interface.
Rob Piked2228692009-10-12 21:18:23 -07002697</p>
2698<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04002699type error interface {
2700 Error() string
Rob Piked2228692009-10-12 21:18:23 -07002701}
2702</pre>
2703<p>
2704A library writer is free to implement this interface with a
2705richer model under the covers, making it possible not only
2706to see the error but also to provide some context.
2707For example, <code>os.Open</code> returns an <code>os.PathError</code>.
2708</p>
2709<pre>
2710// PathError records an error and the operation and
2711// file path that caused it.
2712type PathError struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002713 Op string // "open", "unlink", etc.
2714 Path string // The associated file.
Rob Pike68050ac2011-11-01 21:50:21 -04002715 Err error // Returned by the system call.
Rob Piked2228692009-10-12 21:18:23 -07002716}
2717
Rob Pike68050ac2011-11-01 21:50:21 -04002718func (e *PathError) Error() string {
2719 return e.Op + " " + e.Path + ": " + e.Err.Error()
Rob Piked2228692009-10-12 21:18:23 -07002720}
2721</pre>
2722<p>
Rob Pike68050ac2011-11-01 21:50:21 -04002723<code>PathError</code>'s <code>Error</code> generates
Rob Piked2228692009-10-12 21:18:23 -07002724a string like this:
2725</p>
2726<pre>
2727open /etc/passwx: no such file or directory
2728</pre>
2729<p>
2730Such an error, which includes the problematic file name, the
2731operation, and the operating system error it triggered, is useful even
2732if printed far from the call that caused it;
2733it is much more informative than the plain
2734"no such file or directory".
2735</p>
2736
2737<p>
Nigel Taoca91ce22011-06-17 10:51:10 +10002738When feasible, error strings should identify their origin, such as by having
2739a prefix naming the package that generated the error. For example, in package
Shenghou Ma0532f4d2012-03-21 09:33:55 -07002740<code>image</code>, the string representation for a decoding error due to an
2741unknown format is "image: unknown format".
Nigel Taoca91ce22011-06-17 10:51:10 +10002742</p>
2743
2744<p>
Rob Piked2228692009-10-12 21:18:23 -07002745Callers that care about the precise error details can
2746use a type switch or a type assertion to look for specific
Robert Griesemerb8b308d2012-03-21 14:29:16 -07002747errors and extract details. For <code>PathErrors</code>
Rob Pike68050ac2011-11-01 21:50:21 -04002748this might include examining the internal <code>Err</code>
Rob Piked2228692009-10-12 21:18:23 -07002749field for recoverable failures.
2750</p>
2751
2752<pre>
Rob Pike77f6f162009-12-25 07:13:14 +11002753for try := 0; try &lt; 2; try++ {
Brad Fitzpatricke5102b32012-03-20 16:50:51 -07002754 file, err = os.Create(filename)
Rob Pike163ecda2009-12-16 12:31:18 +11002755 if err == nil {
2756 return
2757 }
Brad Fitzpatricke5102b32012-03-20 16:50:51 -07002758 if e, ok := err.(*os.PathError); ok &amp;&amp; e.Err == syscall.ENOSPC {
Rob Pike163ecda2009-12-16 12:31:18 +11002759 deleteTempFiles() // Recover some space.
2760 continue
2761 }
2762 return
Rob Piked2228692009-10-12 21:18:23 -07002763}
2764</pre>
2765
Rob Pikebb661642011-11-09 16:14:18 -08002766<p>
2767The second <code>if</code> statement here is idiomatic Go.
2768The type assertion <code>err.(*os.PathError)</code> is
2769checked with the "comma ok" idiom (mentioned <a href="#maps">earlier</a>
2770in the context of examining maps).
2771If the type assertion fails, <code>ok</code> will be false, and <code>e</code>
2772will be <code>nil</code>.
2773If it succeeds, <code>ok</code> will be true, which means the
2774error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
2775which we can examine for more information about the error.
2776</p>
2777
Rob Pike99b23a12010-06-18 10:52:37 -07002778<h3 id="panic">Panic</h3>
Rob Pike050905b2010-06-16 13:47:36 -07002779
2780<p>
Rob Pike99b23a12010-06-18 10:52:37 -07002781The usual way to report an error to a caller is to return an
Rob Pike68050ac2011-11-01 21:50:21 -04002782<code>error</code> as an extra return value. The canonical
Rob Pike99b23a12010-06-18 10:52:37 -07002783<code>Read</code> method is a well-known instance; it returns a byte
Rob Pike68050ac2011-11-01 21:50:21 -04002784count and an <code>error</code>. But what if the error is
Rob Pike99b23a12010-06-18 10:52:37 -07002785unrecoverable? Sometimes the program simply cannot continue.
2786</p>
2787
2788<p>
2789For this purpose, there is a built-in function <code>panic</code>
2790that in effect creates a run-time error that will stop the program
2791(but see the next section). The function takes a single argument
2792of arbitrary type&mdash;often a string&mdash;to be printed as the
2793program dies. It's also a way to indicate that something impossible has
2794happened, such as exiting an infinite loop. In fact, the compiler
2795recognizes a <code>panic</code> at the end of a function and
2796suppresses the usual check for a <code>return</code> statement.
2797</p>
2798
2799
2800<pre>
2801// A toy implementation of cube root using Newton's method.
2802func CubeRoot(x float64) float64 {
Andrew Gerrand70f61332011-07-31 15:25:26 -07002803 z := x/3 // Arbitrary initial value
Robert Griesemer76f32282011-02-04 08:43:21 -08002804 for i := 0; i &lt; 1e6; i++ {
Rob Pike99b23a12010-06-18 10:52:37 -07002805 prevz := z
2806 z -= (z*z*z-x) / (3*z*z)
2807 if veryClose(z, prevz) {
2808 return z
2809 }
2810 }
2811 // A million iterations has not converged; something is wrong.
Christopher Wedgwoodc80746a2010-08-19 10:03:58 +10002812 panic(fmt.Sprintf("CubeRoot(%g) did not converge", x))
Rob Pike99b23a12010-06-18 10:52:37 -07002813}
2814</pre>
2815
2816<p>
2817This is only an example but real library functions should
2818avoid <code>panic</code>. If the problem can be masked or worked
2819around, it's always better to let things continue to run rather
2820than taking down the whole program. One possible counterexample
2821is during initialization: if the library truly cannot set itself up,
2822it might be reasonable to panic, so to speak.
2823</p>
2824
2825<pre>
2826var user = os.Getenv("USER")
2827
2828func init() {
2829 if user == "" {
2830 panic("no value for $USER")
2831 }
2832}
2833</pre>
2834
2835<h3 id="recover">Recover</h3>
2836
2837<p>
2838When <code>panic</code> is called, including implicitly for run-time
Robert Griesemerbd4e49f2011-02-02 11:02:56 -08002839errors such as indexing an array out of bounds or failing a type
Rob Pike99b23a12010-06-18 10:52:37 -07002840assertion, it immediately stops execution of the current function
2841and begins unwinding the stack of the goroutine, running any deferred
2842functions along the way. If that unwinding reaches the top of the
2843goroutine's stack, the program dies. However, it is possible to
2844use the built-in function <code>recover</code> to regain control
2845of the goroutine and resume normal execution.
2846</p>
2847
2848<p>
2849A call to <code>recover</code> stops the unwinding and returns the
2850argument passed to <code>panic</code>. Because the only code that
2851runs while unwinding is inside deferred functions, <code>recover</code>
2852is only useful inside deferred functions.
2853</p>
2854
2855<p>
2856One application of <code>recover</code> is to shut down a failing goroutine
2857inside a server without killing the other executing goroutines.
2858</p>
2859
2860<pre>
Robert Griesemer76f32282011-02-04 08:43:21 -08002861func server(workChan &lt;-chan *Work) {
Rob Pike99b23a12010-06-18 10:52:37 -07002862 for work := range workChan {
Rob Pike7ddbe792010-08-24 12:37:51 +10002863 go safelyDo(work)
Rob Pike99b23a12010-06-18 10:52:37 -07002864 }
2865}
2866
2867func safelyDo(work *Work) {
2868 defer func() {
2869 if err := recover(); err != nil {
Rob Pikee787f8272010-10-12 16:56:50 -07002870 log.Println("work failed:", err)
Rob Pike99b23a12010-06-18 10:52:37 -07002871 }
2872 }()
2873 do(work)
2874}
2875</pre>
2876
2877<p>
2878In this example, if <code>do(work)</code> panics, the result will be
2879logged and the goroutine will exit cleanly without disturbing the
2880others. There's no need to do anything else in the deferred closure;
2881calling <code>recover</code> handles the condition completely.
2882</p>
2883
2884<p>
Robert Griesemer76f32282011-02-04 08:43:21 -08002885Because <code>recover</code> always returns <code>nil</code> unless called directly
2886from a deferred function, deferred code can call library routines that themselves
2887use <code>panic</code> and <code>recover</code> without failing. As an example,
2888the deferred function in <code>safelyDo</code> might call a logging function before
2889calling <code>recover</code>, and that logging code would run unaffected
2890by the panicking state.
2891</p>
2892
2893<p>
2894With our recovery pattern in place, the <code>do</code>
Rob Pike99b23a12010-06-18 10:52:37 -07002895function (and anything it calls) can get out of any bad situation
2896cleanly by calling <code>panic</code>. We can use that idea to
2897simplify error handling in complex software. Let's look at an
2898idealized excerpt from the <code>regexp</code> package, which reports
2899parsing errors by calling <code>panic</code> with a local
Rob Pike68050ac2011-11-01 21:50:21 -04002900error type. Here's the definition of <code>Error</code>,
Rob Pike99b23a12010-06-18 10:52:37 -07002901an <code>error</code> method, and the <code>Compile</code> function.
2902</p>
2903
2904<pre>
Rob Pike68050ac2011-11-01 21:50:21 -04002905// Error is the type of a parse error; it satisfies the error interface.
Rob Pike99b23a12010-06-18 10:52:37 -07002906type Error string
Rob Pike68050ac2011-11-01 21:50:21 -04002907func (e Error) Error() string {
Rob Pike99b23a12010-06-18 10:52:37 -07002908 return string(e)
2909}
2910
2911// error is a method of *Regexp that reports parsing errors by
2912// panicking with an Error.
2913func (regexp *Regexp) error(err string) {
2914 panic(Error(err))
2915}
2916
2917// Compile returns a parsed representation of the regular expression.
Rob Pike68050ac2011-11-01 21:50:21 -04002918func Compile(str string) (regexp *Regexp, err error) {
Rob Pike99b23a12010-06-18 10:52:37 -07002919 regexp = new(Regexp)
2920 // doParse will panic if there is a parse error.
2921 defer func() {
2922 if e := recover(); e != nil {
2923 regexp = nil // Clear return value.
2924 err = e.(Error) // Will re-panic if not a parse error.
2925 }
2926 }()
2927 return regexp.doParse(str), nil
2928}
2929</pre>
2930
2931<p>
2932If <code>doParse</code> panics, the recovery block will set the
2933return value to <code>nil</code>&mdash;deferred functions can modify
2934named return values. It then will then check, in the assignment
2935to <code>err</code>, that the problem was a parse error by asserting
Rob Pike68050ac2011-11-01 21:50:21 -04002936that it has the local type <code>Error</code>.
Rob Pike99b23a12010-06-18 10:52:37 -07002937If it does not, the type assertion will fail, causing a run-time error
2938that continues the stack unwinding as though nothing had interrupted
2939it. This check means that if something unexpected happens, such
2940as an array index out of bounds, the code will fail even though we
2941are using <code>panic</code> and <code>recover</code> to handle
2942user-triggered errors.
2943</p>
2944
2945<p>
Rob Pike29d0f022011-01-05 11:39:57 -08002946With error handling in place, the <code>error</code> method
Rob Pike99b23a12010-06-18 10:52:37 -07002947makes it easy to report parse errors without worrying about unwinding
2948the parse stack by hand.
2949</p>
2950
2951<p>
2952Useful though this pattern is, it should be used only within a package.
2953<code>Parse</code> turns its internal <code>panic</code> calls into
Rob Pike68050ac2011-11-01 21:50:21 -04002954<code>error</code> values; it does not expose <code>panics</code>
Rob Pike99b23a12010-06-18 10:52:37 -07002955to its client. That is a good rule to follow.
Rob Pike050905b2010-06-16 13:47:36 -07002956</p>
2957
Rob Pike29d0f022011-01-05 11:39:57 -08002958<p>
2959By the way, this re-panic idiom changes the panic value if an actual
2960error occurs. However, both the original and new failures will be
2961presented in the crash report, so the root cause of the problem will
2962still be visible. Thus this simple re-panic approach is usually
2963sufficient&mdash;it's a crash after all&mdash;but if you want to
2964display only the original value, you can write a little more code to
2965filter unexpected problems and re-panic with the original error.
2966That's left as an exercise for the reader.
2967</p>
2968
Rob Pike050905b2010-06-16 13:47:36 -07002969
Rob Pike31053d42009-11-04 17:29:20 -08002970<h2 id="web_server">A web server</h2>
2971
2972<p>
2973Let's finish with a complete Go program, a web server.
2974This one is actually a kind of web re-server.
2975Google provides a service at
2976<a href="http://chart.apis.google.com">http://chart.apis.google.com</a>
2977that does automatic formatting of data into charts and graphs.
2978It's hard to use interactively, though,
2979because you need to put the data into the URL as a query.
2980The program here provides a nicer interface to one form of data: given a short piece of text,
2981it calls on the chart server to produce a QR code, a matrix of boxes that encode the
2982text.
2983That image can be grabbed with your cell phone's camera and interpreted as,
2984for instance, a URL, saving you typing the URL into the phone's tiny keyboard.
2985</p>
2986<p>
2987Here's the complete program.
2988An explanation follows.
2989</p>
Shenghou Ma5b7562d2012-09-03 03:49:03 +08002990{{code "/doc/progs/eff_qr.go" `/package/` `$`}}
Rob Pike31053d42009-11-04 17:29:20 -08002991<p>
2992The pieces up to <code>main</code> should be easy to follow.
2993The one flag sets a default HTTP port for our server. The template
2994variable <code>templ</code> is where the fun happens. It builds an HTML template
2995that will be executed by the server to display the page; more about
2996that in a moment.
2997</p>
2998<p>
2999The <code>main</code> function parses the flags and, using the mechanism
3000we talked about above, binds the function <code>QR</code> to the root path
3001for the server. Then <code>http.ListenAndServe</code> is called to start the
3002server; it blocks while the server runs.
3003</p>
3004<p>
3005<code>QR</code> just receives the request, which contains form data, and
Russ Cox24ce19c2009-11-08 01:07:53 -08003006executes the template on the data in the form value named <code>s</code>.
Rob Pike31053d42009-11-04 17:29:20 -08003007</p>
3008<p>
Rob Pikef3fc0092012-09-13 13:41:13 -07003009The template package <code>html/template</code> is powerful;
Rob Pike31053d42009-11-04 17:29:20 -08003010this program just touches on its capabilities.
Rob Pikef3fc0092012-09-13 13:41:13 -07003011In essence, it rewrites a piece of HTML text on the fly by substituting elements derived
Rob Pike31053d42009-11-04 17:29:20 -08003012from data items passed to <code>templ.Execute</code>, in this case the
Rob Pikef3fc0092012-09-13 13:41:13 -07003013form value.
Rob Pike31053d42009-11-04 17:29:20 -08003014Within the template text (<code>templateStr</code>),
Rob Piked1a3eda2011-08-21 09:46:19 +10003015double-brace-delimited pieces denote template actions.
Russ Coxa40065a2012-03-08 08:39:20 -05003016The piece from <code>{{html "{{if .}}"}}</code>
3017to <code>{{html "{{end}}"}}</code> executes only if the value of the current data item, called <code>.</code> (dot),
Rob Piked1a3eda2011-08-21 09:46:19 +10003018is non-empty.
3019That is, when the string is empty, this piece of the template is suppressed.
Rob Pike31053d42009-11-04 17:29:20 -08003020</p>
3021<p>
Rob Pikef3fc0092012-09-13 13:41:13 -07003022The two snippets <code>{{html "{{.}}"}}</code> say to show the data presented to
3023the template—the query string—on the web page.
3024The HTML template package automatically provides appropriate escaping so the
3025text is safe to display.
Rob Pike31053d42009-11-04 17:29:20 -08003026</p>
3027<p>
3028The rest of the template string is just the HTML to show when the page loads.
Rob Pikef3fc0092012-09-13 13:41:13 -07003029If this is too quick an explanation, see the <a href="/pkg/html/template/">documentation</a>
Rob Pike31053d42009-11-04 17:29:20 -08003030for the template package for a more thorough discussion.
3031</p>
3032<p>
Rob Pike40747952012-03-25 11:34:51 +11003033And there you have it: a useful web server in a few lines of code plus some
Rob Pike31053d42009-11-04 17:29:20 -08003034data-driven HTML text.
3035Go is powerful enough to make a lot happen in a few lines.
3036</p>
3037
Rob Pike6f89f3f2009-10-20 17:32:16 -07003038<!--
Rob Pike3e740792009-10-05 14:48:57 -07003039TODO
Rob Pike163ecda2009-12-16 12:31:18 +11003040<pre>
3041verifying implementation
3042type Color uint32
Oling Cate93891f2012-09-18 08:50:24 -07003043
Rob Pike163ecda2009-12-16 12:31:18 +11003044// Check that Color implements image.Color and image.Image
3045var _ image.Color = Black
3046var _ image.Image = Black
3047</pre>
Rob Pike8aec6122009-09-02 16:41:41 -07003048-->
Rob Pike6f89f3f2009-10-20 17:32:16 -07003049