blob: a32179298e8de6869213c0cb9e49647df17293d5 [file] [log] [blame]
Robert Griesemer53440da2009-10-01 14:08:00 -07001<!-- Effective Go -->
Rob Pike69d13b22009-09-29 11:57:28 -07002
Russ Cox94439982009-06-25 09:38:35 -07003<h2 id="introduction">Introduction</h2>
4
5<p>
Rob Pike3e740792009-10-05 14:48:57 -07006Go is a new language. Although it borrows ideas from
7existing languages,
8it has unusual properties that make effective Go programs
Russ Cox24ce19c2009-11-08 01:07:53 -08009different in character from programs written in its relatives.
Rob Pike22140a12009-08-19 13:24:24 -070010A straightforward translation of a C++ or Java program into Go
Rob Pike3e740792009-10-05 14:48:57 -070011is unlikely to produce a satisfactory result&mdash;Java programs
Rob Pike22140a12009-08-19 13:24:24 -070012are written in Java, not Go.
13On the other hand, thinking about the problem from a Go
14perspective could produce a successful but quite different
15program.
16In other words,
17to write Go well, it's important to understand its properties
Rob Pikefe287e72009-08-03 14:07:19 -070018and idioms.
Rob Pike22140a12009-08-19 13:24:24 -070019It's also important to know the established conventions for
20programming in Go, such as naming, formatting, program
21construction, and so on, so that programs you write
22will be easy for other Go programmers to understand.
Rob Pikefe287e72009-08-03 14:07:19 -070023</p>
24
25<p>
Rob Pike22140a12009-08-19 13:24:24 -070026This document gives tips for writing clear, idiomatic Go code.
Russ Cox94439982009-06-25 09:38:35 -070027It augments the <a href="go_spec.html">language specification</a>
28and the <a href="go_tutorial.html">tutorial</a>, both of which you
Rob Pikeeaf6a342009-07-06 15:15:56 -070029should read first.
Russ Cox94439982009-06-25 09:38:35 -070030</p>
31
Rob Pike99b23a12010-06-18 10:52:37 -070032<h3 id="examples">Examples</h3>
Russ Cox94439982009-06-25 09:38:35 -070033
34<p>
Rob Pike88407262009-10-16 11:13:40 -070035The <a href="/src/pkg/">Go package sources</a>
Russ Cox94439982009-06-25 09:38:35 -070036are intended to serve not
37only as the core library but also as examples of how to
Rob Pike22140a12009-08-19 13:24:24 -070038use the language.
39If you have a question about how to approach a problem or how something
Russ Cox24ce19c2009-11-08 01:07:53 -080040might be implemented, they can provide answers, ideas and
Rob Pike22140a12009-08-19 13:24:24 -070041background.
Russ Cox94439982009-06-25 09:38:35 -070042</p>
43
Russ Cox94439982009-06-25 09:38:35 -070044
45<h2 id="formatting">Formatting</h2>
46
47<p>
48Formatting issues are the most contentious
49but the least consequential.
Rob Pike22140a12009-08-19 13:24:24 -070050People can adapt to different formatting styles
51but it's better if they don't have to, and
52less time is devoted to the topic
53if everyone adheres to the same style.
54The problem is how to approach this Utopia without a long
55prescriptive style guide.
Russ Cox94439982009-06-25 09:38:35 -070056</p>
57
Russ Cox94439982009-06-25 09:38:35 -070058<p>
Rob Pike11e4db72009-08-19 16:39:25 -070059With Go we take an unusual
Rob Pike22140a12009-08-19 13:24:24 -070060approach and let the machine
61take care of most formatting issues.
62A program, <code>gofmt</code>, reads a Go program
63and emits the source in a standard style of indentation
64and vertical alignment, retaining and if necessary
65reformatting comments.
66If you want to know how to handle some new layout
67situation, run <code>gofmt</code>; if the answer doesn't
68seem right, fix the program (or file a bug), don't work around it.
Rob Piked1a3b982009-07-31 11:41:30 -070069</p>
70
Rob Piked1a3b982009-07-31 11:41:30 -070071<p>
Rob Pike22140a12009-08-19 13:24:24 -070072As an example, there's no need to spend time lining up
73the comments on the fields of a structure.
74<code>Gofmt</code> will do that for you. Given the
75declaration
Russ Cox94439982009-06-25 09:38:35 -070076</p>
77
Rob Pike22140a12009-08-19 13:24:24 -070078<pre>
79type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +110080 name string // name of the object
81 value int // its value
Rob Pike22140a12009-08-19 13:24:24 -070082}
83</pre>
Russ Cox94439982009-06-25 09:38:35 -070084
85<p>
Russ Cox24ce19c2009-11-08 01:07:53 -080086<code>gofmt</code> will line up the columns:
Russ Cox94439982009-06-25 09:38:35 -070087</p>
88
Rob Pike22140a12009-08-19 13:24:24 -070089<pre>
90type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +110091 name string // name of the object
92 value int // its value
Rob Pike22140a12009-08-19 13:24:24 -070093}
94</pre>
Russ Cox94439982009-06-25 09:38:35 -070095
96<p>
Rob Pike22140a12009-08-19 13:24:24 -070097All code in the libraries has been formatted with <code>gofmt</code>.
Russ Cox94439982009-06-25 09:38:35 -070098</p>
99
Russ Cox94439982009-06-25 09:38:35 -0700100
Rob Pike22140a12009-08-19 13:24:24 -0700101<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700102Some formatting details remain. Very briefly,
Russ Cox94439982009-06-25 09:38:35 -0700103</p>
104
Rob Pike22140a12009-08-19 13:24:24 -0700105<dl>
Rob Pike163ecda2009-12-16 12:31:18 +1100106 <dt>Indentation</dt>
107 <dd>We use tabs for indentation and <code>gofmt</code> emits them by default.
108 Use spaces only if you must.
109 </dd>
110 <dt>Line length</dt>
111 <dd>
112 Go has no line length limit. Don't worry about overflowing a punched card.
113 If a line feels too long, wrap it and indent with an extra tab.
114 </dd>
115 <dt>Parentheses</dt>
116 <dd>
117 Go needs fewer parentheses: control structures (<code>if</code>,
118 <code>for</code>, <code>switch</code>) do not require parentheses in
119 their syntax.
120 Also, the operator precedence hierarchy is shorter and clearer, so
Rob Pike22140a12009-08-19 13:24:24 -0700121<pre>
122x&lt;&lt;8 + y&lt;&lt;16
123</pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100124 means what the spacing implies.
125 </dd>
Rob Pike22140a12009-08-19 13:24:24 -0700126</dl>
127
Rob Pike6f89f3f2009-10-20 17:32:16 -0700128<h2 id="commentary">Commentary</h2>
Rob Pike22140a12009-08-19 13:24:24 -0700129
Russ Cox94439982009-06-25 09:38:35 -0700130<p>
Robert Griesemer53440da2009-10-01 14:08:00 -0700131Go provides C-style <code>/* */</code> block comments
Russ Cox94439982009-06-25 09:38:35 -0700132and C++-style <code>//</code> line comments.
Rob Pike11e4db72009-08-19 16:39:25 -0700133Line comments are the norm;
134block comments appear mostly as package comments and
135are also useful to disable large swaths of code.
Russ Cox94439982009-06-25 09:38:35 -0700136</p>
137
Rob Pike11e4db72009-08-19 16:39:25 -0700138<p>
139The program—and web server—<code>godoc</code> processes
140Go source files to extract documentation about the contents of the
141package.
142Comments that appear before top-level declarations, with no intervening newlines,
143are extracted along with the declaration to serve as explanatory text for the item.
144The nature and style of these comments determines the
145quality of the documentation <code>godoc</code> produces.
146</p>
Rob Piked951ce42009-07-31 17:54:00 -0700147
148<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700149Every package should have a <i>package comment</i>, a block
Rob Piked951ce42009-07-31 17:54:00 -0700150comment preceding the package clause.
Rob Pike11e4db72009-08-19 16:39:25 -0700151For multi-file packages, the package comment only needs to be
152present in one file, and any one will do.
153The package comment should introduce the package and
Rob Piked951ce42009-07-31 17:54:00 -0700154provide information relevant to the package as a whole.
Rob Pike11e4db72009-08-19 16:39:25 -0700155It will appear first on the <code>godoc</code> page and
156should set up the detailed documentation that follows.
Rob Piked951ce42009-07-31 17:54:00 -0700157</p>
158
159<pre>
160/*
Rob Pike163ecda2009-12-16 12:31:18 +1100161 The regexp package implements a simple library for
162 regular expressions.
Rob Piked951ce42009-07-31 17:54:00 -0700163
Rob Pike163ecda2009-12-16 12:31:18 +1100164 The syntax of the regular expressions accepted is:
Rob Piked951ce42009-07-31 17:54:00 -0700165
Rob Pike163ecda2009-12-16 12:31:18 +1100166 regexp:
167 concatenation { '|' concatenation }
168 concatenation:
169 { closure }
170 closure:
171 term [ '*' | '+' | '?' ]
172 term:
173 '^'
174 '$'
175 '.'
176 character
177 '[' [ '^' ] character-ranges ']'
178 '(' regexp ')'
Rob Piked951ce42009-07-31 17:54:00 -0700179*/
180package regexp
181</pre>
182
183<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700184If the package is simple, the package comment can be brief.
Rob Piked951ce42009-07-31 17:54:00 -0700185</p>
186
187<pre>
188// The path package implements utility routines for
189// manipulating slash-separated filename paths.
190</pre>
191
Russ Cox94439982009-06-25 09:38:35 -0700192<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700193Comments do not need extra formatting such as banners of stars.
194The generated output may not even be presented in a fixed-width font, so don't depend
Rob Pike430d4622009-10-20 12:30:39 -0700195on spacing for alignment&mdash;<code>godoc</code>, like <code>gofmt</code>,
Rob Pike11e4db72009-08-19 16:39:25 -0700196takes care of that.
Rob Pike6095ff32011-02-16 22:35:31 -0800197The comments are uninterpreted plain text, so HTML and other
Rob Pike11e4db72009-08-19 16:39:25 -0700198annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should
199not be used.
Rob Pike6095ff32011-02-16 22:35:31 -0800200Depending on the context, <code>godoc</code> might not even
201reformat comments, so make sure they look good straight up:
202use correct spelling, punctuation, and sentence structure,
203fold long lines, and so on.
Russ Cox94439982009-06-25 09:38:35 -0700204</p>
205
206<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700207Inside a package, any comment immediately preceding a top-level declaration
208serves as a <i>doc comment</i> for that declaration.
Russ Cox94439982009-06-25 09:38:35 -0700209Every exported (capitalized) name in a program should
Rob Pike11e4db72009-08-19 16:39:25 -0700210have a doc comment.
Russ Cox94439982009-06-25 09:38:35 -0700211</p>
212
213<p>
Rob Pike7ddbe792010-08-24 12:37:51 +1000214Doc comments work best as complete sentences, which allow
Rob Pike11e4db72009-08-19 16:39:25 -0700215a wide variety of automated presentations.
Russ Cox94439982009-06-25 09:38:35 -0700216The first sentence should be a one-sentence summary that
Rob Pikeb95048f2009-10-13 14:32:21 -0700217starts with the name being declared.
Russ Cox94439982009-06-25 09:38:35 -0700218</p>
219
220<pre>
Rob Pike11e4db72009-08-19 16:39:25 -0700221// Compile parses a regular expression and returns, if successful, a Regexp
222// object that can be used to match against text.
223func Compile(str string) (regexp *Regexp, error os.Error) {
Russ Cox94439982009-06-25 09:38:35 -0700224</pre>
225
226<p>
Rob Piked951ce42009-07-31 17:54:00 -0700227Go's declaration syntax allows grouping of declarations.
Rob Pike11e4db72009-08-19 16:39:25 -0700228A single doc comment can introduce a group of related constants or variables.
229Since the whole declaration is presented, such a comment can often be perfunctory.
Rob Piked951ce42009-07-31 17:54:00 -0700230</p>
231
232<pre>
Rob Pike11e4db72009-08-19 16:39:25 -0700233// Error codes returned by failures to parse an expression.
234var (
Rob Pike163ecda2009-12-16 12:31:18 +1100235 ErrInternal = os.NewError("internal error")
236 ErrUnmatchedLpar = os.NewError("unmatched '('")
237 ErrUnmatchedRpar = os.NewError("unmatched ')'")
238 ...
Rob Piked951ce42009-07-31 17:54:00 -0700239)
240</pre>
241
242<p>
Rob Pike11e4db72009-08-19 16:39:25 -0700243Even for private names, grouping can also indicate relationships between items,
Russ Cox24ce19c2009-11-08 01:07:53 -0800244such as the fact that a set of variables is protected by a mutex.
Rob Piked951ce42009-07-31 17:54:00 -0700245</p>
246
247<pre>
Rob Piked951ce42009-07-31 17:54:00 -0700248var (
Rob Pike163ecda2009-12-16 12:31:18 +1100249 countLock sync.Mutex
250 inputCount uint32
251 outputCount uint32
Rob Pike6c088592010-06-14 22:40:35 -0700252 errorCount uint32
Rob Piked951ce42009-07-31 17:54:00 -0700253)
254</pre>
255
Russ Cox94439982009-06-25 09:38:35 -0700256<h2 id="names">Names</h2>
257
Russ Cox94439982009-06-25 09:38:35 -0700258<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700259Names are as important in Go as in any other language.
260In some cases they even have semantic effect: for instance,
261the visibility of a name outside a package is determined by whether its
Rob Pikec2b64182009-11-01 20:54:11 -0800262first character is upper case.
Rob Pikef0ccd402009-08-20 15:39:41 -0700263It's therefore worth spending a little time talking about naming conventions
264in Go programs.
Russ Cox94439982009-06-25 09:38:35 -0700265</p>
266
Rob Pikef0ccd402009-08-20 15:39:41 -0700267
268<h3 id="package-names">Package names</h3>
Russ Cox94439982009-06-25 09:38:35 -0700269
270<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700271When a package is imported, the package name becomes an accessor for the
272contents. After
273</p>
274
275<pre>
276import "bytes"
277</pre>
278
279<p>
280the importing package can talk about <code>bytes.Buffer</code>. It's
281helpful if everyone using the package can use the same name to refer to
282its contents, which implies that the package name should be good:
283short, concise, evocative. By convention, packages are given
284lower case, single-word names; there should be no need for underscores
285or mixedCaps.
286Err on the side of brevity, since everyone using your
287package will be typing that name.
288And don't worry about collisions <i>a priori</i>.
289The package name is only the default name for imports; it need not be unique
290across all source code, and in the rare case of a collision the
291importing package can choose a different name to use locally.
Rob Pike3e740792009-10-05 14:48:57 -0700292In any case, confusion is rare because the file name in the import
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -0800293determines just which package is being used.
Rob Pikef0ccd402009-08-20 15:39:41 -0700294</p>
295
296<p>
297Another convention is that the package name is the base name of
298its source directory;
299the package in <code>src/pkg/container/vector</code>
Russ Cox24ce19c2009-11-08 01:07:53 -0800300is imported as <code>"container/vector"</code> but has name <code>vector</code>,
Russ Cox94439982009-06-25 09:38:35 -0700301not <code>container_vector</code> and not <code>containerVector</code>.
Russ Cox94439982009-06-25 09:38:35 -0700302</p>
303
304<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700305The importer of a package will use the name to refer to its contents
306(the <code>import .</code> notation is intended mostly for tests and other
Russ Cox24ce19c2009-11-08 01:07:53 -0800307unusual situations), so exported names in the package can use that fact
Rob Pikef0ccd402009-08-20 15:39:41 -0700308to avoid stutter.
309For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>,
310not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>,
311which is a clear, concise name.
312Moreover,
313because imported entities are always addressed with their package name, <code>bufio.Reader</code>
314does not conflict with <code>io.Reader</code>.
Rob Pikeacf4dd42009-12-02 13:46:02 -0800315Similarly, the function to make new instances of <code>ring.Ring</code>&mdash;which
Russ Cox24ce19c2009-11-08 01:07:53 -0800316is the definition of a <em>constructor</em> in Go&mdash;would
Rob Pikeacf4dd42009-12-02 13:46:02 -0800317normally be called <code>NewRing</code>, but since
318<code>Ring</code> is the only type exported by the package, and since the
319package is called <code>ring</code>, it's called just <code>New</code>.
320Clients of the package see that as <code>ring.New</code>.
Rob Pikef0ccd402009-08-20 15:39:41 -0700321Use the package structure to help you choose good names.
Russ Cox94439982009-06-25 09:38:35 -0700322</p>
323
Rob Pikef0ccd402009-08-20 15:39:41 -0700324<p>
325Another short example is <code>once.Do</code>;
326<code>once.Do(setup)</code> reads well and would not be improved by
327writing <code>once.DoOrWaitUntilDone(setup)</code>.
328Long names don't automatically make things more readable.
329If the name represents something intricate or subtle, it's usually better
330to write a helpful doc comment than to attempt to put all the information
331into the name.
332</p>
333
334<h3 id="interface-names">Interface names</h3>
Russ Cox94439982009-06-25 09:38:35 -0700335
336<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700337By convention, one-method interfaces are named by
Russ Cox94439982009-06-25 09:38:35 -0700338the method name plus the -er suffix: <code>Reader</code>,
Rob Pikef0ccd402009-08-20 15:39:41 -0700339<code>Writer</code>, <code>Formatter</code> etc.
Russ Cox94439982009-06-25 09:38:35 -0700340</p>
341
Russ Cox94439982009-06-25 09:38:35 -0700342<p>
Rob Pikef0ccd402009-08-20 15:39:41 -0700343There are a number of such names and it's productive to honor them and the function
344names they capture.
345<code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>,
346<code>String</code> and so on have
Russ Cox94439982009-06-25 09:38:35 -0700347canonical signatures and meanings. To avoid confusion,
348don't give your method one of those names unless it
349has the same signature and meaning.
350Conversely, if your type implements a method with the
351same meaning as a method on a well-known type,
Rob Pikef0ccd402009-08-20 15:39:41 -0700352give it the same name and signature;
353call your string-converter method <code>String</code> not <code>ToString</code>.
Russ Cox94439982009-06-25 09:38:35 -0700354</p>
355
Rob Pikef0ccd402009-08-20 15:39:41 -0700356<h3 id="mixed-caps">MixedCaps</h3>
357
Russ Cox94439982009-06-25 09:38:35 -0700358<p>
Rob Pike3e740792009-10-05 14:48:57 -0700359Finally, the convention in Go is to use <code>MixedCaps</code>
Rob Pikef0ccd402009-08-20 15:39:41 -0700360or <code>mixedCaps</code> rather than underscores to write
361multiword names.
Russ Cox94439982009-06-25 09:38:35 -0700362</p>
363
Rob Pikec4099762009-08-23 14:00:28 -0700364<h2 id="semicolons">Semicolons</h2>
Russ Cox94439982009-06-25 09:38:35 -0700365
366<p>
Rob Pike163ecda2009-12-16 12:31:18 +1100367Like C, Go's formal grammar uses semicolons to terminate statements;
368unlike C, those semicolons do not appear in the source.
369Instead the lexer uses a simple rule to insert semicolons automatically
370as it scans, so the input text is mostly free of them.
Russ Cox94439982009-06-25 09:38:35 -0700371</p>
372
Rob Pike163ecda2009-12-16 12:31:18 +1100373<p>
374The rule is this. If the last token before a newline is an identifier
375(which includes words like <code>int</code> and <code>float64</code>),
376a basic literal such as a number or string constant, or one of the
377tokens
378</p>
Rob Piked951ce42009-07-31 17:54:00 -0700379<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100380break continue fallthrough return ++ -- ) }
381</pre>
382<p>
383the lexer always inserts a semicolon after the token.
384This could be summarized as, &ldquo;if the newline comes
385after a token that could end a statement, add a semicolon&rdquo;.
386</p>
387
388<p>
389A semicolon can also be omitted immediately before a closing brace,
390so a statement such as
391</p>
392<pre>
Rob Pikec4099762009-08-23 14:00:28 -0700393 go func() { for { dst &lt;- &lt;-src } }()
Rob Pike22140a12009-08-19 13:24:24 -0700394</pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100395<p>
396needs no semicolons.
397Idiomatic Go programs have semicolons only in places such as
398<code>for</code> loop clauses, to separate the initializer, condition, and
399continuation elements. They are also necessary to separate multiple
400statements on a line, should you write code that way.
401</p>
Rob Pike401c0b32009-08-13 11:29:05 -0700402
Russ Cox94439982009-06-25 09:38:35 -0700403<p>
Rob Pike163ecda2009-12-16 12:31:18 +1100404One caveat. You should never put the opening brace of a
405control structure (<code>if</code>, <code>for</code>, <code>switch</code>,
406or <code>select</code>) on the next line. If you do, a semicolon
407will be inserted before the brace, which could cause unwanted
408effects. Write them like this
Rob Pikec4099762009-08-23 14:00:28 -0700409</p>
410
411<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100412if i &lt; f() {
Rob Pike163ecda2009-12-16 12:31:18 +1100413 g()
Rob Pikec4099762009-08-23 14:00:28 -0700414}
Rob Pike163ecda2009-12-16 12:31:18 +1100415</pre>
416<p>
417not like this
418</p>
419<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100420if i &lt; f() // wrong!
Rob Pike163ecda2009-12-16 12:31:18 +1100421{ // wrong!
422 g()
423}
Rob Pikec4099762009-08-23 14:00:28 -0700424</pre>
425
Rob Pikec4099762009-08-23 14:00:28 -0700426
427<h2 id="control-structures">Control structures</h2>
428
429<p>
Rob Pike6c088592010-06-14 22:40:35 -0700430The control structures of Go are related to those of C but differ
Rob Pikec4099762009-08-23 14:00:28 -0700431in important ways.
432There is no <code>do</code> or <code>while</code> loop, only a
433slightly generalized
434<code>for</code>;
435<code>switch</code> is more flexible;
436<code>if</code> and <code>switch</code> accept an optional
437initialization statement like that of <code>for</code>;
438and there are new control structures including a type switch and a
439multiway communications multiplexer, <code>select</code>.
Rob Pike3e740792009-10-05 14:48:57 -0700440The syntax is also slightly different:
441parentheses are not required
Rob Pikec4099762009-08-23 14:00:28 -0700442and the bodies must always be brace-delimited.
443</p>
444
445<h3 id="if">If</h3>
446
447<p>
448In Go a simple <code>if</code> looks like this:
449</p>
450<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100451if x &gt; 0 {
Rob Pikec4099762009-08-23 14:00:28 -0700452 return y
453}
454</pre>
455
456<p>
457Mandatory braces encourage writing simple <code>if</code> statements
458on multiple lines. It's good style to do so anyway,
459especially when the body contains a control statement such as a
460<code>return</code> or <code>break</code>.
461</p>
462
463<p>
464Since <code>if</code> and <code>switch</code> accept an initialization
Rob Pikeb95048f2009-10-13 14:32:21 -0700465statement, it's common to see one used to set up a local variable.
Rob Pikec4099762009-08-23 14:00:28 -0700466</p>
467
468<pre>
469if err := file.Chmod(0664); err != nil {
Rob Pikee787f8272010-10-12 16:56:50 -0700470 log.Print(err)
Rob Pike163ecda2009-12-16 12:31:18 +1100471 return err
Rob Pikec4099762009-08-23 14:00:28 -0700472}
473</pre>
474
475<p id="else">
476In the Go libraries, you'll find that
477when an <code>if</code> statement doesn't flow into the next statement—that is,
Rob Piked1a3b982009-07-31 11:41:30 -0700478the body ends in <code>break</code>, <code>continue</code>,
Rob Pikec4099762009-08-23 14:00:28 -0700479<code>goto</code>, or <code>return</code>—the unnecessary
480<code>else</code> is omitted.
Russ Cox94439982009-06-25 09:38:35 -0700481</p>
482
483<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100484f, err := os.Open(name, os.O_RDONLY, 0)
Russ Cox94439982009-06-25 09:38:35 -0700485if err != nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100486 return err
Russ Cox94439982009-06-25 09:38:35 -0700487}
Rob Pike163ecda2009-12-16 12:31:18 +1100488codeUsing(f)
Russ Cox94439982009-06-25 09:38:35 -0700489</pre>
490
Rob Pikec4099762009-08-23 14:00:28 -0700491<p>
492This is a example of a common situation where code must analyze a
493sequence of error possibilities. The code reads well if the
494successful flow of control runs down the page, eliminating error cases
495as they arise. Since error cases tend to end in <code>return</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700496statements, the resulting code needs no <code>else</code> statements.
Rob Pikec4099762009-08-23 14:00:28 -0700497</p>
498
499<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100500f, err := os.Open(name, os.O_RDONLY, 0)
Rob Pikec4099762009-08-23 14:00:28 -0700501if err != nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100502 return err
Rob Pikec4099762009-08-23 14:00:28 -0700503}
Rob Pike163ecda2009-12-16 12:31:18 +1100504d, err := f.Stat()
Rob Pikec4099762009-08-23 14:00:28 -0700505if err != nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100506 return err
Rob Pikec4099762009-08-23 14:00:28 -0700507}
Rob Pike163ecda2009-12-16 12:31:18 +1100508codeUsing(f, d)
Rob Pikec4099762009-08-23 14:00:28 -0700509</pre>
510
511
Rob Pike8aec6122009-09-02 16:41:41 -0700512<h3 id="for">For</h3>
513
514<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700515The Go <code>for</code> loop is similar to&mdash;but not the same as&mdash;C's.
Rob Pike8aec6122009-09-02 16:41:41 -0700516It unifies <code>for</code>
517and <code>while</code> and there is no <code>do-while</code>.
Rob Pikeb95048f2009-10-13 14:32:21 -0700518There are three forms, only one of which has semicolons.
Rob Pike8aec6122009-09-02 16:41:41 -0700519</p>
520<pre>
Rob Pikec77c3b02009-09-08 17:11:57 -0700521// Like a C for
Rob Pike8aec6122009-09-02 16:41:41 -0700522for init; condition; post { }
523
Rob Pikec77c3b02009-09-08 17:11:57 -0700524// Like a C while
Rob Pike8aec6122009-09-02 16:41:41 -0700525for condition { }
526
527// Like a C for(;;)
528for { }
529</pre>
530
531<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700532Short declarations make it easy to declare the index variable right in the loop.
Rob Pike8aec6122009-09-02 16:41:41 -0700533</p>
534<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100535sum := 0
Rob Pike77f6f162009-12-25 07:13:14 +1100536for i := 0; i &lt; 10; i++ {
Rob Pike8aec6122009-09-02 16:41:41 -0700537 sum += i
538}
539</pre>
540
541<p>
Rob Pikec2b64182009-11-01 20:54:11 -0800542If you're looping over an array, slice, string, or map,
543or reading from a channel, a <code>range</code> clause can
544manage the loop for you.
Rob Pike8aec6122009-09-02 16:41:41 -0700545</p>
546<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100547var m map[string]int
548sum := 0
Rob Pike3e740792009-10-05 14:48:57 -0700549for _, value := range m { // key is unused
Rob Pike8aec6122009-09-02 16:41:41 -0700550 sum += value
551}
552</pre>
553
554<p>
Rob Pikec2b64182009-11-01 20:54:11 -0800555For strings, the <code>range</code> does more work for you, breaking out individual
556Unicode characters by parsing the UTF-8 (erroneous encodings consume one byte and produce the
Rob Pikec77c3b02009-09-08 17:11:57 -0700557replacement rune U+FFFD). The loop
558</p>
559<pre>
560for pos, char := range "日本語" {
561 fmt.Printf("character %c starts at byte position %d\n", char, pos)
562}
563</pre>
564<p>
565prints
566</p>
567<pre>
568character æ—¥ starts at byte position 0
569character 本 starts at byte position 3
570character 語 starts at byte position 6
571</pre>
572
573<p>
Rob Pike8aec6122009-09-02 16:41:41 -0700574Finally, since Go has no comma operator and <code>++</code> and <code>--</code>
575are statements not expressions, if you want to run multiple variables in a <code>for</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700576you should use parallel assignment.
Rob Pike8aec6122009-09-02 16:41:41 -0700577</p>
578<pre>
579// Reverse a
Rob Pike77f6f162009-12-25 07:13:14 +1100580for i, j := 0, len(a)-1; i &lt; j; i, j = i+1, j-1 {
Rob Pike163ecda2009-12-16 12:31:18 +1100581 a[i], a[j] = a[j], a[i]
Rob Pike8aec6122009-09-02 16:41:41 -0700582}
583</pre>
584
Russ Cox94439982009-06-25 09:38:35 -0700585<h3 id="switch">Switch</h3>
586
587<p>
Rob Pikeeaf6a342009-07-06 15:15:56 -0700588Go's <code>switch</code> is more general than C's.
Rob Pikec4099762009-08-23 14:00:28 -0700589The expressions need not be constants or even integers,
590the cases are evaluated top to bottom until a match is found,
591and if the <code>switch</code> has no expression it switches on
592<code>true</code>.
Rob Pikeb95048f2009-10-13 14:32:21 -0700593It's therefore possible&mdash;and idiomatic&mdash;to write an
Rob Pikec4099762009-08-23 14:00:28 -0700594<code>if</code>-<code>else</code>-<code>if</code>-<code>else</code>
Rob Pikeb95048f2009-10-13 14:32:21 -0700595chain as a <code>switch</code>.
Russ Cox94439982009-06-25 09:38:35 -0700596</p>
597
Rob Pikeeaf6a342009-07-06 15:15:56 -0700598<pre>
599func unhex(c byte) byte {
600 switch {
601 case '0' &lt;= c &amp;&amp; c &lt;= '9':
602 return c - '0'
603 case 'a' &lt;= c &amp;&amp; c &lt;= 'f':
604 return c - 'a' + 10
605 case 'A' &lt;= c &amp;&amp; c &lt;= 'F':
606 return c - 'A' + 10
607 }
608 return 0
609}
610</pre>
611
Rob Pikec4099762009-08-23 14:00:28 -0700612<p>
613There is no automatic fall through, but cases can be presented
Rob Pikeb95048f2009-10-13 14:32:21 -0700614in comma-separated lists.
Rob Pikeeaf6a342009-07-06 15:15:56 -0700615<pre>
616func shouldEscape(c byte) bool {
617 switch c {
618 case ' ', '?', '&amp;', '=', '#', '+', '%':
619 return true
620 }
621 return false
622}
623</pre>
624
Rob Pikec4099762009-08-23 14:00:28 -0700625<p>
626Here's a comparison routine for byte arrays that uses two
627<code>switch</code> statements:
Russ Cox94439982009-06-25 09:38:35 -0700628<pre>
Rob Piked951ce42009-07-31 17:54:00 -0700629// Compare returns an integer comparing the two byte arrays
630// lexicographically.
Rob Pikec4099762009-08-23 14:00:28 -0700631// 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 -0700632func Compare(a, b []byte) int {
633 for i := 0; i &lt; len(a) &amp;&amp; i &lt; len(b); i++ {
634 switch {
635 case a[i] &gt; b[i]:
636 return 1
637 case a[i] &lt; b[i]:
638 return -1
639 }
640 }
641 switch {
642 case len(a) &lt; len(b):
643 return -1
644 case len(a) &gt; len(b):
645 return 1
646 }
647 return 0
648}
649</pre>
650
Rob Piked2228692009-10-12 21:18:23 -0700651<p>
652A switch can also be used to discover the dynamic type of an interface
653variable. Such a <em>type switch</em> uses the syntax of a type
654assertion with the keyword <code>type</code> inside the parentheses.
655If the switch declares a variable in the expression, the variable will
656have the corresponding type in each clause.
657</p>
658<pre>
659switch t := interfaceValue.(type) {
660default:
Rob Pike163ecda2009-12-16 12:31:18 +1100661 fmt.Printf("unexpected type %T", t) // %T prints type
Rob Piked2228692009-10-12 21:18:23 -0700662case bool:
Rob Pike163ecda2009-12-16 12:31:18 +1100663 fmt.Printf("boolean %t\n", t)
Rob Piked2228692009-10-12 21:18:23 -0700664case int:
Rob Pike163ecda2009-12-16 12:31:18 +1100665 fmt.Printf("integer %d\n", t)
Rob Piked2228692009-10-12 21:18:23 -0700666case *bool:
Rob Pike163ecda2009-12-16 12:31:18 +1100667 fmt.Printf("pointer to boolean %t\n", *t)
Rob Piked2228692009-10-12 21:18:23 -0700668case *int:
Rob Pike163ecda2009-12-16 12:31:18 +1100669 fmt.Printf("pointer to integer %d\n", *t)
Rob Piked2228692009-10-12 21:18:23 -0700670}
671</pre>
672
Rob Pikea5d6f832009-09-14 10:40:44 -0700673<h2 id="functions">Functions</h2>
674
675<h3 id="multiple-returns">Multiple return values</h3>
676
677<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -0800678One of Go's unusual features is that functions and methods
679can return multiple values. This can be used to
Rob Pike3e740792009-10-05 14:48:57 -0700680improve on a couple of clumsy idioms in C programs: in-band
Rob Pikec2b64182009-11-01 20:54:11 -0800681error returns (such as <code>-1</code> for <code>EOF</code>)
Rob Pikea5d6f832009-09-14 10:40:44 -0700682and modifying an argument.
683</p>
684
685<p>
Russ Cox24ce19c2009-11-08 01:07:53 -0800686In C, a write error is signaled by a negative count with the
Rob Pikea5d6f832009-09-14 10:40:44 -0700687error code secreted away in a volatile location.
688In Go, <code>Write</code>
Russ Cox24ce19c2009-11-08 01:07:53 -0800689can return a count <i>and</i> an error: &ldquo;Yes, you wrote some
690bytes but not all of them because you filled the device&rdquo;.
Rob Pikea5d6f832009-09-14 10:40:44 -0700691The signature of <code>*File.Write</code> in package <code>os</code> is:
692</p>
693
694<pre>
695func (file *File) Write(b []byte) (n int, err Error)
696</pre>
697
698<p>
699and as the documentation says, it returns the number of bytes
700written and a non-nil <code>Error</code> when <code>n</code>
701<code>!=</code> <code>len(b)</code>.
702This is a common style; see the section on error handling for more examples.
703</p>
704
705<p>
706A similar approach obviates the need to pass a pointer to a return
Rob Pike3e740792009-10-05 14:48:57 -0700707value to simulate a reference parameter.
708Here's a simple-minded function to
Rob Pikea5d6f832009-09-14 10:40:44 -0700709grab a number from a position in a byte array, returning the number
710and the next position.
711</p>
712
713<pre>
714func nextInt(b []byte, i int) (int, int) {
Rob Pike77f6f162009-12-25 07:13:14 +1100715 for ; i &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
Rob Pike163ecda2009-12-16 12:31:18 +1100716 }
717 x := 0
Rob Pike77f6f162009-12-25 07:13:14 +1100718 for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
Rob Pike163ecda2009-12-16 12:31:18 +1100719 x = x*10 + int(b[i])-'0'
720 }
721 return x, i
Rob Pikea5d6f832009-09-14 10:40:44 -0700722}
723</pre>
724
725<p>
726You could use it to scan the numbers in an input array <code>a</code> like this:
727</p>
728
729<pre>
Rob Pike77f6f162009-12-25 07:13:14 +1100730 for i := 0; i &lt; len(a); {
Rob Pike163ecda2009-12-16 12:31:18 +1100731 x, i = nextInt(a, i)
732 fmt.Println(x)
733 }
Rob Pikea5d6f832009-09-14 10:40:44 -0700734</pre>
735
736<h3 id="named-results">Named result parameters</h3>
737
738<p>
739The return or result "parameters" of a Go function can be given names and
740used as regular variables, just like the incoming parameters.
Rob Pike3e740792009-10-05 14:48:57 -0700741When named, they are initialized to the zero values for their types when
Rob Pikea5d6f832009-09-14 10:40:44 -0700742the function begins; if the function executes a <code>return</code> statement
Robert Griesemer53440da2009-10-01 14:08:00 -0700743with no arguments, the current values of the result parameters are
Rob Pikea5d6f832009-09-14 10:40:44 -0700744used as the returned values.
745</p>
746
747<p>
748The names are not mandatory but they can make code shorter and clearer:
749they're documentation.
750If we name the results of <code>nextInt</code> it becomes
751obvious which returned <code>int</code>
752is which.
753</p>
754
755<pre>
756func nextInt(b []byte, pos int) (value, nextPos int) {
757</pre>
758
759<p>
760Because named results are initialized and tied to an unadorned return, they can simplify
761as well as clarify. Here's a version
762of <code>io.ReadFull</code> that uses them well:
763</p>
764
765<pre>
766func ReadFull(r Reader, buf []byte) (n int, err os.Error) {
Rob Pike77f6f162009-12-25 07:13:14 +1100767 for len(buf) &gt; 0 &amp;&amp; err == nil {
Rob Pike163ecda2009-12-16 12:31:18 +1100768 var nr int
769 nr, err = r.Read(buf)
770 n += nr
771 buf = buf[nr:len(buf)]
772 }
773 return
Rob Pikea5d6f832009-09-14 10:40:44 -0700774}
775</pre>
776
Rob Pike050905b2010-06-16 13:47:36 -0700777<h3 id="defer">Defer</h3>
778
779<p>
780Go's <code>defer</code> statement schedules a function call (the
781<i>deferred</i> function) to be run immediately before the function
782executing the <code>defer</code> returns. It's an unusual but
783effective way to deal with situations such as resources that must be
784released regardless of which path a function takes to return. The
785canonical examples are unlocking a mutex or closing a file.
786</p>
787
788<pre>
789// Contents returns the file's contents as a string.
790func Contents(filename string) (string, os.Error) {
791 f, err := os.Open(filename, os.O_RDONLY, 0)
792 if err != nil {
793 return "", err
794 }
795 defer f.Close() // f.Close will run when we're finished.
796
797 var result []byte
798 buf := make([]byte, 100)
799 for {
800 n, err := f.Read(buf[0:])
Kyle Consalus009aebd2010-12-01 11:59:13 -0800801 result = append(result, buf[0:n]...) // append is discussed later.
Rob Pike050905b2010-06-16 13:47:36 -0700802 if err != nil {
803 if err == os.EOF {
804 break
805 }
806 return "", err // f will be closed if we return here.
807 }
808 }
809 return string(result), nil // f will be closed if we return here.
810}
811</pre>
812
813<p>
814Deferring a function like this has two advantages. First, it
815guarantees that you will never forget to close the file, a mistake
816that's easy to make if you later edit the function to add a new return
817path. Second, it means that the close sits near the open,
818which is much clearer than placing it at the end of the function.
819</p>
820
821<p>
Rob Pikee787f8272010-10-12 16:56:50 -0700822The arguments to the deferred function (which include the receiver if
Rob Pike050905b2010-06-16 13:47:36 -0700823the function is a method) are evaluated when the <i>defer</i>
824executes, not when the <i>call</i> executes. Besides avoiding worries
825about variables changing values as the function executes, this means
826that a single deferred call site can defer multiple function
827executions. Here's a silly example.
828</p>
829
830<pre>
Robert Griesemer76f32282011-02-04 08:43:21 -0800831for i := 0; i &lt; 5; i++ {
Rob Pike050905b2010-06-16 13:47:36 -0700832 defer fmt.Printf("%d ", i)
833}
834</pre>
835
836<p>
837Deferred functions are executed in LIFO order, so this code will cause
838<code>4 3 2 1 0</code> to be printed when the function returns. A
839more plausible example is a simple way to trace function execution
840through the program. We could write a couple of simple tracing
841routines like this:
842</p>
843
844<pre>
845func trace(s string) { fmt.Println("entering:", s) }
846func untrace(s string) { fmt.Println("leaving:", s) }
847
848// Use them like this:
849func a() {
850 trace("a")
851 defer untrace("a")
852 // do something....
853}
854</pre>
855
856<p>
857We can do better by exploiting the fact that arguments to deferred
858functions are evaluated when the <code>defer</code> executes. The
859tracing routine can set up the argument to the untracing routine.
860This example:
861</p>
862
863<pre>
864func trace(s string) string {
865 fmt.Println("entering:", s)
866 return s
867}
868
869func un(s string) {
870 fmt.Println("leaving:", s)
871}
872
873func a() {
874 defer un(trace("a"))
875 fmt.Println("in a")
876}
877
878func b() {
879 defer un(trace("b"))
880 fmt.Println("in b")
881 a()
882}
883
884func main() {
885 b()
886}
887</pre>
888
889<p>
890prints
891</p>
892
893<pre>
894entering: b
895in b
896entering: a
897in a
898leaving: a
899leaving: b
900</pre>
901
902<p>
903For programmers accustomed to block-level resource management from
904other languages, <code>defer</code> may seem peculiar, but its most
905interesting and powerful applications come precisely from the fact
906that it's not block-based but function based. In the section on
907<code>panic</code> and <code>recover</code> we'll see an example.
908</p>
909
Rob Pike2e5a1362009-09-27 17:59:36 -0700910<h2 id="data">Data</h2>
911
912<h3 id="allocation_new">Allocation with <code>new()</code></h3>
913
914<p>
915Go has two allocation primitives, <code>new()</code> and <code>make()</code>.
916They do different things and apply to different types, which can be confusing,
917but the rules are simple.
918Let's talk about <code>new()</code> first.
919It's a built-in function essentially the same as its namesakes
Russ Cox24ce19c2009-11-08 01:07:53 -0800920in other languages: <code>new(T)</code> allocates zeroed storage for a new item of type
Rob Pike2e5a1362009-09-27 17:59:36 -0700921<code>T</code> and returns its address, a value of type <code>*T</code>.
922In Go terminology, it returns a pointer to a newly allocated zero value of type
923<code>T</code>.
924</p>
925
926<p>
927Since the memory returned by <code>new()</code> is zeroed, it's helpful to arrange that the
928zeroed object can be used without further initialization. This means a user of
929the data structure can create one with <code>new()</code> and get right to
930work.
931For example, the documentation for <code>bytes.Buffer</code> states that
932"the zero value for <code>Buffer</code> is an empty buffer ready to use."
933Similarly, <code>sync.Mutex</code> does not
934have an explicit constructor or <code>Init</code> method.
935Instead, the zero value for a <code>sync.Mutex</code>
936is defined to be an unlocked mutex.
937</p>
938
939<p>
Rob Pikeb95048f2009-10-13 14:32:21 -0700940The zero-value-is-useful property works transitively. Consider this type declaration.
Rob Pike2e5a1362009-09-27 17:59:36 -0700941</p>
942
943<pre>
944type SyncedBuffer struct {
Rob Pike163ecda2009-12-16 12:31:18 +1100945 lock sync.Mutex
946 buffer bytes.Buffer
Rob Pike2e5a1362009-09-27 17:59:36 -0700947}
948</pre>
949
950<p>
951Values of type <code>SyncedBuffer</code> are also ready to use immediately upon allocation
952or just declaration. In this snippet, both <code>p</code> and <code>v</code> will work
Rob Pikeb95048f2009-10-13 14:32:21 -0700953correctly without further arrangement.
Rob Pike2e5a1362009-09-27 17:59:36 -0700954</p>
955
956<pre>
Rob Pike163ecda2009-12-16 12:31:18 +1100957p := new(SyncedBuffer) // type *SyncedBuffer
958var v SyncedBuffer // type SyncedBuffer
Rob Pike2e5a1362009-09-27 17:59:36 -0700959</pre>
960
961<h3 id="composite_literals">Constructors and composite literals</h3>
962
963<p>
964Sometimes the zero value isn't good enough and an initializing
965constructor is necessary, as in this example derived from
Rob Pikeb95048f2009-10-13 14:32:21 -0700966package <code>os</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -0700967</p>
968
969<pre>
970func NewFile(fd int, name string) *File {
Rob Pike163ecda2009-12-16 12:31:18 +1100971 if fd &lt; 0 {
972 return nil
973 }
974 f := new(File)
975 f.fd = fd
976 f.name = name
977 f.dirinfo = nil
978 f.nepipe = 0
979 return f
Rob Pike2e5a1362009-09-27 17:59:36 -0700980}
981</pre>
982
983<p>
Rob Pike430d4622009-10-20 12:30:39 -0700984There's a lot of boiler plate in there. We can simplify it
Rob Pike2e5a1362009-09-27 17:59:36 -0700985using a <i>composite literal</i>, which is
986an expression that creates a
987new instance each time it is evaluated.
988</p>
989
990
991<pre>
992func NewFile(fd int, name string) *File {
Rob Pike163ecda2009-12-16 12:31:18 +1100993 if fd &lt; 0 {
994 return nil
995 }
996 f := File{fd, name, nil, 0}
997 return &amp;f
Rob Pike2e5a1362009-09-27 17:59:36 -0700998}
999</pre>
1000
1001<p>
1002Note that it's perfectly OK to return the address of a local variable;
1003the storage associated with the variable survives after the function
1004returns.
Rob Pike3e740792009-10-05 14:48:57 -07001005In fact, taking the address of a composite literal
1006allocates a fresh instance each time it is evaluated,
Rob Pikeb95048f2009-10-13 14:32:21 -07001007so we can combine these last two lines.
Rob Pike2e5a1362009-09-27 17:59:36 -07001008</p>
1009
1010<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001011 return &amp;File{fd, name, nil, 0}
Rob Pike2e5a1362009-09-27 17:59:36 -07001012</pre>
1013
1014<p>
1015The fields of a composite literal are laid out in order and must all be present.
1016However, by labeling the elements explicitly as <i>field</i><code>:</code><i>value</i>
1017pairs, the initializers can appear in any
1018order, with the missing ones left as their respective zero values. Thus we could say
1019</p>
1020
1021<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001022 return &amp;File{fd: fd, name: name}
Rob Pike2e5a1362009-09-27 17:59:36 -07001023</pre>
1024
1025<p>
1026As a limiting case, if a composite literal contains no fields at all, it creates
Russ Cox24ce19c2009-11-08 01:07:53 -08001027a 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 -07001028</p>
1029
Rob Pike2e5a1362009-09-27 17:59:36 -07001030<p>
1031Composite literals can also be created for arrays, slices, and maps,
1032with the field labels being indices or map keys as appropriate.
Russ Cox24ce19c2009-11-08 01:07:53 -08001033In these examples, the initializations work regardless of the values of <code>Enone</code>,
Rob Pikeb95048f2009-10-13 14:32:21 -07001034<code>Eio</code>, and <code>Einval</code>, as long as they are distinct.
Rob Pike2e5a1362009-09-27 17:59:36 -07001035</p>
1036
1037<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001038a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
1039s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
1040m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
Rob Pike2e5a1362009-09-27 17:59:36 -07001041</pre>
1042
1043<h3 id="allocation_make">Allocation with <code>make()</code></h3>
1044
1045<p>
1046Back to allocation.
1047The built-in function <code>make(T, </code><i>args</i><code>)</code> serves
1048a purpose different from <code>new(T)</code>.
1049It creates slices, maps, and channels only, and it returns an initialized (not zero)
1050value of type <code>T</code>, not <code>*T</code>.
1051The reason for the distinction
1052is that these three types are, under the covers, references to data structures that
1053must be initialized before use.
1054A slice, for example, is a three-item descriptor
1055containing a pointer to the data (inside an array), the length, and the
1056capacity; until those items are initialized, the slice is <code>nil</code>.
Robert Griesemer53440da2009-10-01 14:08:00 -07001057For slices, maps, and channels,
Rob Pike2e5a1362009-09-27 17:59:36 -07001058<code>make</code> initializes the internal data structure and prepares
1059the value for use.
1060For instance,
1061</p>
1062
1063<pre>
1064make([]int, 10, 100)
1065</pre>
1066
1067<p>
1068allocates an array of 100 ints and then creates a slice
1069structure with length 10 and a capacity of 100 pointing at the first
107010 elements of the array.
1071(When making a slice, the capacity can be omitted; see the section on slices
1072for more information.)
1073In contrast, <code>new([]int)</code> returns a pointer to a newly allocated, zeroed slice
1074structure, that is, a pointer to a <code>nil</code> slice value.
1075
1076<p>
1077These examples illustrate the difference between <code>new()</code> and
Rob Pikeb95048f2009-10-13 14:32:21 -07001078<code>make()</code>.
Rob Pike2e5a1362009-09-27 17:59:36 -07001079</p>
1080
1081<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001082var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
Andrew Gerrand766c3ff2010-02-22 14:51:22 -08001083var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
Rob Pike2e5a1362009-09-27 17:59:36 -07001084
1085// Unnecessarily complex:
Rob Pike163ecda2009-12-16 12:31:18 +11001086var p *[]int = new([]int)
1087*p = make([]int, 100, 100)
Rob Pike2e5a1362009-09-27 17:59:36 -07001088
1089// Idiomatic:
Rob Pike163ecda2009-12-16 12:31:18 +11001090v := make([]int, 100)
Rob Pike2e5a1362009-09-27 17:59:36 -07001091</pre>
1092
1093<p>
Russ Cox24ce19c2009-11-08 01:07:53 -08001094Remember that <code>make()</code> applies only to maps, slices and channels
1095and does not return a pointer.
Rob Pike2e5a1362009-09-27 17:59:36 -07001096To obtain an explicit pointer allocate with <code>new()</code>.
1097</p>
1098
1099<h3 id="arrays">Arrays</h3>
1100
1101<p>
1102Arrays are useful when planning the detailed layout of memory and sometimes
Russ Cox24ce19c2009-11-08 01:07:53 -08001103can help avoid allocation, but primarily
Rob Pike2e5a1362009-09-27 17:59:36 -07001104they are a building block for slices, the subject of the next section.
1105To lay the foundation for that topic, here are a few words about arrays.
1106</p>
1107
1108<p>
1109There are major differences between the ways arrays work in Go and C.
Rob Pikeb95048f2009-10-13 14:32:21 -07001110In Go,
Rob Pike2e5a1362009-09-27 17:59:36 -07001111</p>
1112<ul>
1113<li>
1114Arrays are values. Assigning one array to another copies all the elements.
1115</li>
1116<li>
1117In particular, if you pass an array to a function, it
1118will receive a <i>copy</i> of the array, not a pointer to it.
1119<li>
1120The size of an array is part of its type. The types <code>[10]int</code>
1121and <code>[20]int</code> are distinct.
1122</li>
1123</ul>
1124
1125<p>
1126The value property can be useful but also expensive; if you want C-like behavior and efficiency,
Rob Pikeb95048f2009-10-13 14:32:21 -07001127you can pass a pointer to the array.
Rob Pike2e5a1362009-09-27 17:59:36 -07001128</p>
1129
1130<pre>
Rob Pike80e25fc2011-01-19 23:07:38 -05001131func Sum(a *[3]float64) (sum float64) {
Rob Pike163ecda2009-12-16 12:31:18 +11001132 for _, v := range *a {
1133 sum += v
1134 }
1135 return
Rob Pike2e5a1362009-09-27 17:59:36 -07001136}
1137
Rob Pike80e25fc2011-01-19 23:07:38 -05001138array := [...]float64{7.0, 8.5, 9.1}
Rob Pike163ecda2009-12-16 12:31:18 +11001139x := Sum(&amp;array) // Note the explicit address-of operator
Rob Pike2e5a1362009-09-27 17:59:36 -07001140</pre>
1141
1142<p>
1143But even this style isn't idiomatic Go. Slices are.
1144</p>
1145
1146<h3 id="slices">Slices</h3>
1147
1148<p>
Rob Pike3e740792009-10-05 14:48:57 -07001149Slices wrap arrays to give a more general, powerful, and convenient
1150interface to sequences of data. Except for items with explicit
1151dimension such as transformation matrices, most array programming in
1152Go is done with slices rather than simple arrays.
1153</p>
1154<p>
1155Slices are <i>reference types</i>, which means that if you assign one
1156slice to another, both refer to the same underlying array. For
1157instance, if a function takes a slice argument, changes it makes to
1158the elements of the slice will be visible to the caller, analogous to
1159passing a pointer to the underlying array. A <code>Read</code>
Russ Cox24ce19c2009-11-08 01:07:53 -08001160function can therefore accept a slice argument rather than a pointer
1161and a count; the length within the slice sets an upper
Rob Pike3e740792009-10-05 14:48:57 -07001162limit of how much data to read. Here is the signature of the
1163<code>Read</code> method of the <code>File</code> type in package
1164<code>os</code>:
1165</p>
1166<pre>
1167func (file *File) Read(buf []byte) (n int, err os.Error)
1168</pre>
1169<p>
1170The method returns the number of bytes read and an error value, if
1171any. To read into the first 32 bytes of a larger buffer
Rob Pikeb95048f2009-10-13 14:32:21 -07001172<code>b</code>, <i>slice</i> (here used as a verb) the buffer.
Rob Pike3e740792009-10-05 14:48:57 -07001173</p>
1174<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001175 n, err := f.Read(buf[0:32])
Rob Pike3e740792009-10-05 14:48:57 -07001176</pre>
1177<p>
1178Such slicing is common and efficient. In fact, leaving efficiency aside for
Rob Pikeb95048f2009-10-13 14:32:21 -07001179the moment, this snippet would also read the first 32 bytes of the buffer.
Rob Pike3e740792009-10-05 14:48:57 -07001180</p>
1181<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001182 var n int
1183 var err os.Error
Rob Pike77f6f162009-12-25 07:13:14 +11001184 for i := 0; i &lt; 32; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11001185 nbytes, e := f.Read(buf[i:i+1]) // Read one byte.
1186 if nbytes == 0 || e != nil {
1187 err = e
1188 break
1189 }
1190 n += nbytes
1191 }
Rob Pike3e740792009-10-05 14:48:57 -07001192</pre>
1193<p>
1194The length of a slice may be changed as long as it still fits within
Rob Pikeb95048f2009-10-13 14:32:21 -07001195the limits of the underlying array; just assign it to a slice of
Rob Pike3e740792009-10-05 14:48:57 -07001196itself. The <i>capacity</i> of a slice, accessible by the built-in
1197function <code>cap</code>, reports the maximum length the slice may
1198assume. Here is a function to append data to a slice. If the data
1199exceeds the capacity, the slice is reallocated. The
1200resulting slice is returned. The function uses the fact that
1201<code>len</code> and <code>cap</code> are legal when applied to the
1202<code>nil</code> slice, and return 0.
1203</p>
1204<pre>
1205func Append(slice, data[]byte) []byte {
Rob Pike163ecda2009-12-16 12:31:18 +11001206 l := len(slice)
Rob Pike77f6f162009-12-25 07:13:14 +11001207 if l + len(data) &gt; cap(slice) { // reallocate
Rob Pike163ecda2009-12-16 12:31:18 +11001208 // Allocate double what's needed, for future growth.
1209 newSlice := make([]byte, (l+len(data))*2)
Ian Lance Taylorcd242fb2010-04-13 13:05:29 -07001210 // The copy function is predeclared and works for any slice type.
1211 copy(newSlice, slice)
Rob Pike163ecda2009-12-16 12:31:18 +11001212 slice = newSlice
1213 }
1214 slice = slice[0:l+len(data)]
1215 for i, c := range data {
1216 slice[l+i] = c
1217 }
1218 return slice
Rob Pike3e740792009-10-05 14:48:57 -07001219}
1220</pre>
1221<p>
1222We must return the slice afterwards because, although <code>Append</code>
1223can modify the elements of <code>slice</code>, the slice itself (the run-time data
1224structure holding the pointer, length, and capacity) is passed by value.
Rob Pike0808b192010-11-01 21:46:04 -07001225<p>
1226The idea of appending to a slice is so useful it's captured by the
1227<code>append</code> built-in function. To understand that function's
1228design, though, we need a little more information, so we'll return
1229to it later.
Rob Pike2e5a1362009-09-27 17:59:36 -07001230</p>
1231
1232
1233<h3 id="maps">Maps</h3>
Rob Pike9dfe4042009-10-12 14:51:12 -07001234
1235<p>
1236Maps are a convenient and powerful built-in data structure to associate
1237values of different types.
Russ Cox24ce19c2009-11-08 01:07:53 -08001238The key can be of any type for which the equality operator is defined,
1239such as integers,
Rob Pike80e25fc2011-01-19 23:07:38 -05001240floating point and complex numbers,
1241strings, pointers, and interfaces (as long as the dynamic type
Russ Cox24ce19c2009-11-08 01:07:53 -08001242supports equality). Structs, arrays and slices cannot be used as map keys,
1243because equality is not defined on those types.
Rob Pike9dfe4042009-10-12 14:51:12 -07001244Like slices, maps are a reference type. If you pass a map to a function
1245that changes the contents of the map, the changes will be visible
1246in the caller.
1247</p>
1248<p>
1249Maps can be constructed using the usual composite literal syntax
1250with colon-separated key-value pairs,
1251so it's easy to build them during initialization.
1252</p>
1253<pre>
1254var timeZone = map[string] int {
Rob Pike163ecda2009-12-16 12:31:18 +11001255 "UTC": 0*60*60,
1256 "EST": -5*60*60,
1257 "CST": -6*60*60,
1258 "MST": -7*60*60,
1259 "PST": -8*60*60,
Rob Pike9dfe4042009-10-12 14:51:12 -07001260}
1261</pre>
1262<p>
1263Assigning and fetching map values looks syntactically just like
1264doing the same for arrays except that the index doesn't need to
Rob Pike47106422010-03-30 11:21:50 -07001265be an integer.
1266</p>
1267<pre>
1268offset := timeZone["EST"]
1269</pre>
1270<p>
1271An attempt to fetch a map value with a key that
1272is not present in the map will return the zero value for the type
1273of the entries
1274in the map. For instance, if the map contains integers, looking
1275up a non-existent key will return <code>0</code>.
1276</p>
1277<p>
1278Sometimes you need to distinguish a missing entry from
1279a zero value. Is there an entry for <code>"UTC"</code>
1280or is that zero value because it's not in the map at all?
1281You can discriminate with a form of multiple assignment.
Rob Pike9dfe4042009-10-12 14:51:12 -07001282</p>
1283<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001284var seconds int
1285var ok bool
Rob Pike9dfe4042009-10-12 14:51:12 -07001286seconds, ok = timeZone[tz]
1287</pre>
1288<p>
1289For obvious reasons this is called the &ldquo;comma ok&rdquo; idiom.
1290In this example, if <code>tz</code> is present, <code>seconds</code>
1291will be set appropriately and <code>ok</code> will be true; if not,
1292<code>seconds</code> will be set to zero and <code>ok</code> will
1293be false.
Rob Pike47106422010-03-30 11:21:50 -07001294Here's a function that puts it together with a nice error report:
Rob Pike9dfe4042009-10-12 14:51:12 -07001295</p>
1296<pre>
1297func offset(tz string) int {
Rob Pike163ecda2009-12-16 12:31:18 +11001298 if seconds, ok := timeZone[tz]; ok {
1299 return seconds
1300 }
Rob Pikee787f8272010-10-12 16:56:50 -07001301 log.Println("unknown time zone", tz)
Rob Pike163ecda2009-12-16 12:31:18 +11001302 return 0
Rob Pike9dfe4042009-10-12 14:51:12 -07001303}
1304</pre>
1305<p>
1306To test for presence in the map without worrying about the actual value,
1307you can use the <em>blank identifier</em>, a simple underscore (<code>_</code>).
1308The blank identifier can be assigned or declared with any value of any type, with the
Rob Pike47106422010-03-30 11:21:50 -07001309value discarded harmlessly. For testing just presence in a map, use the blank
Rob Pike9dfe4042009-10-12 14:51:12 -07001310identifier in place of the usual variable for the value.
1311</p>
1312<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001313_, present := timeZone[tz]
Rob Pike9dfe4042009-10-12 14:51:12 -07001314</pre>
1315<p>
1316To delete a map entry, turn the multiple assignment around by placing
1317an extra boolean on the right; if the boolean is false, the entry
1318is deleted. It's safe to do this even if the key is already absent
1319from the map.
1320</p>
1321<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001322timeZone["PDT"] = 0, false // Now on Standard Time
Rob Pike9dfe4042009-10-12 14:51:12 -07001323</pre>
Rob Pike47106422010-03-30 11:21:50 -07001324
Rob Pike2e5a1362009-09-27 17:59:36 -07001325<h3 id="printing">Printing</h3>
1326
Rob Pike9dfe4042009-10-12 14:51:12 -07001327<p>
1328Formatted printing in Go uses a style similar to C's <code>printf</code>
1329family but is richer and more general. The functions live in the <code>fmt</code>
1330package and have capitalized names: <code>fmt.Printf</code>, <code>fmt.Fprintf</code>,
1331<code>fmt.Sprintf</code> and so on. The string functions (<code>Sprintf</code> etc.)
1332return a string rather than filling in a provided buffer.
1333</p>
1334<p>
1335You don't need to provide a format string. For each of <code>Printf</code>,
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001336<code>Fprintf</code> and <code>Sprintf</code> there is another pair
Rob Pike9dfe4042009-10-12 14:51:12 -07001337of functions, for instance <code>Print</code> and <code>Println</code>.
1338These functions do not take a format string but instead generate a default
Rob Pike7ddbe792010-08-24 12:37:51 +10001339format for each argument. The <code>Println</code> versions also insert a blank
1340between arguments and append a newline to the output while
1341the <code>Print</code> versions add blanks only if the operand on neither side is a string.
Rob Pike9dfe4042009-10-12 14:51:12 -07001342In this example each line produces the same output.
1343</p>
1344<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001345fmt.Printf("Hello %d\n", 23)
1346fmt.Fprint(os.Stdout, "Hello ", 23, "\n")
Rob Pike7ddbe792010-08-24 12:37:51 +10001347fmt.Println("Hello", 23)
Rob Pike163ecda2009-12-16 12:31:18 +11001348fmt.Println(fmt.Sprint("Hello ", 23))
Rob Pike9dfe4042009-10-12 14:51:12 -07001349</pre>
1350<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001351As mentioned in
1352the <a href="go_tutorial.html">tutorial</a>, <code>fmt.Fprint</code>
1353and friends take as a first argument any object
Rob Pike9dfe4042009-10-12 14:51:12 -07001354that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code>
1355and <code>os.Stderr</code> are familiar instances.
1356</p>
1357<p>
1358Here things start to diverge from C. First, the numeric formats such as <code>%d</code>
1359do not take flags for signedness or size; instead, the printing routines use the
1360type of the argument to decide these properties.
1361</p>
1362<pre>
Rob Pike77f6f162009-12-25 07:13:14 +11001363var x uint64 = 1&lt;&lt;64 - 1
Rob Pike163ecda2009-12-16 12:31:18 +11001364fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))
Rob Pike9dfe4042009-10-12 14:51:12 -07001365</pre>
1366<p>
1367prints
1368</p>
1369<pre>
137018446744073709551615 ffffffffffffffff; -1 -1
1371</pre>
1372<p>
1373If you just want the default conversion, such as decimal for integers, you can use
1374the catchall format <code>%v</code> (for &ldquo;value&rdquo;); the result is exactly
1375what <code>Print</code> and <code>Println</code> would produce.
1376Moreover, that format can print <em>any</em> value, even arrays, structs, and
1377maps. Here is a print statement for the time zone map defined in the previous section.
1378</p>
1379<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001380fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001381</pre>
1382<p>
1383which gives output
1384</p>
1385<pre>
1386map[CST:-21600 PST:-28800 EST:-18000 UTC:0 MST:-25200]
1387</pre>
1388<p>
1389For maps the keys may be output in any order, of course.
1390When printing a struct, the modified format <code>%+v</code> annotates the
1391fields of the structure with their names, and for any value the alternate
1392format <code>%#v</code> prints the value in full Go syntax.
1393</p>
1394<pre>
1395type T struct {
Rob Pike163ecda2009-12-16 12:31:18 +11001396 a int
1397 b float
1398 c string
Rob Pike9dfe4042009-10-12 14:51:12 -07001399}
Rob Pike163ecda2009-12-16 12:31:18 +11001400t := &amp;T{ 7, -2.35, "abc\tdef" }
1401fmt.Printf("%v\n", t)
1402fmt.Printf("%+v\n", t)
1403fmt.Printf("%#v\n", t)
1404fmt.Printf("%#v\n", timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001405</pre>
1406<p>
1407prints
1408</p>
1409<pre>
1410&amp;{7 -2.35 abc def}
1411&amp;{a:7 b:-2.35 c:abc def}
1412&amp;main.T{a:7, b:-2.35, c:"abc\tdef"}
1413map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200}
1414</pre>
1415<p>
1416(Note the ampersands.)
1417That quoted string format is also available through <code>%q</code> when
1418applied to a value of type <code>string</code> or <code>[]byte</code>;
1419the alternate format <code>%#q</code> will use backquotes instead if possible.
1420Also, <code>%x</code> works on strings and arrays of bytes as well as on integers,
1421generating a long hexadecimal string, and with
1422a space in the format (<code>%&nbsp;x</code>) it puts spaces between the bytes.
1423</p>
1424<p>
1425Another handy format is <code>%T</code>, which prints the <em>type</em> of a value.
1426<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001427fmt.Printf(&quot;%T\n&quot;, timeZone)
Rob Pike9dfe4042009-10-12 14:51:12 -07001428</pre>
1429<p>
1430prints
1431</p>
1432<pre>
1433map[string] int
1434</pre>
1435<p>
1436If you want to control the default format for a custom type, all that's required is to define
Rob Pikeb95048f2009-10-13 14:32:21 -07001437a method <code>String() string</code> on the type.
1438For our simple type <code>T</code>, that might look like this.
Rob Pike9dfe4042009-10-12 14:51:12 -07001439</p>
1440<pre>
1441func (t *T) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001442 return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
Rob Pike9dfe4042009-10-12 14:51:12 -07001443}
Rob Pike163ecda2009-12-16 12:31:18 +11001444fmt.Printf("%v\n", t)
Rob Pike9dfe4042009-10-12 14:51:12 -07001445</pre>
1446<p>
1447to print in the format
1448</p>
1449<pre>
14507/-2.35/"abc\tdef"
1451</pre>
1452<p>
1453Our <code>String()</code> method is able to call <code>Sprintf</code> because the
1454print routines are fully reentrant and can be used recursively.
1455We 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 -07001456The signature of <code>Printf</code> uses the type <code>...interface{}</code>
1457for its final argument to specify that an arbitrary number of parameters (of arbitrary type)
1458can appear after the format.
Rob Pike9dfe4042009-10-12 14:51:12 -07001459</p>
1460<pre>
Rob Pike6c088592010-06-14 22:40:35 -07001461func Printf(format string, v ...interface{}) (n int, errno os.Error) {
Rob Pike9dfe4042009-10-12 14:51:12 -07001462</pre>
1463<p>
Rob Pike6c088592010-06-14 22:40:35 -07001464Within the function <code>Printf</code>, <code>v</code> acts like a variable of type
1465<code>[]interface{}</code> but if it is passed to another variadic function, it acts like
1466a regular list of arguments.
1467Here is the implementation of the
Rob Pikee787f8272010-10-12 16:56:50 -07001468function <code>log.Println</code> we used above. It passes its arguments directly to
Rob Pike9dfe4042009-10-12 14:51:12 -07001469<code>fmt.Sprintln</code> for the actual formatting.
1470</p>
1471<pre>
Rob Pikee787f8272010-10-12 16:56:50 -07001472// Println prints to the standard logger in the manner of fmt.Println.
1473func Println(v ...interface{}) {
1474 std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string)
Rob Pike9dfe4042009-10-12 14:51:12 -07001475}
1476</pre>
1477<p>
Rob Pike70d0b6b22010-11-03 11:09:43 -07001478We 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 -07001479compiler to treat <code>v</code> as a list of arguments; otherwise it would just pass
1480<code>v</code> as a single slice argument.
1481<p>
Rob Pike9dfe4042009-10-12 14:51:12 -07001482There's even more to printing than we've covered here. See the <code>godoc</code> documentation
1483for package <code>fmt</code> for the details.
1484</p>
Rob Pike6c088592010-06-14 22:40:35 -07001485<p>
1486By the way, a <code>...</code> parameter can be of a specific type, for instance <code>...int</code>
1487for a min function that chooses the least of a list of integers:
1488</p>
1489<pre>
1490func Min(a ...int) int {
1491 min := int(^uint(0) >> 1) // largest int
1492 for _, i := range a {
Robert Griesemer76f32282011-02-04 08:43:21 -08001493 if i &lt; min {
Rob Pike050905b2010-06-16 13:47:36 -07001494 min = i
1495 }
Rob Pike6c088592010-06-14 22:40:35 -07001496 }
1497 return min
1498}
1499</pre>
Rob Pike9dfe4042009-10-12 14:51:12 -07001500
Rob Pike0808b192010-11-01 21:46:04 -07001501<h3 id="append">Append</h3>
1502<p>
1503Now we have the missing piece we needed to explain the design of
1504the <code>append</code> built-in function. The signature of <code>append</code>
1505is different from our custom <code>Append</code> function above.
1506Schematically, it's like this:
1507<pre>
1508func append(slice []<i>T</i>, elements...T) []<i>T</i>
1509</pre>
1510where <i>T</i> is a placeholder for any given type. You can't
1511actually write a function in Go where the type <code>T</code>
1512is determined by the caller.
1513That's why <code>append</code> is built in: it needs support from the
1514compiler.
1515<p>
1516What <code>append</code> does is append the elements to the end of
1517the slice and return the result. The result needs to be returned
1518because, as with our hand-written <code>Append</code>, the underlying
1519array may change. This simple example
1520<pre>
1521x := []int{1,2,3}
1522x = append(x, 4, 5, 6)
1523fmt.Println(x)
1524</pre>
1525prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a
1526little like <code>Printf</code>, collecting an arbitrary number of
1527arguments.
1528<p>
1529But what if we wanted to do what our <code>Append</code> does and
1530append a slice to a slice? Easy: use <code>...</code> at the call
1531site, just as we did in the call to <code>Output</code> above. This
1532snippet produces identical output to the one above.
1533<pre>
1534x := []int{1,2,3}
1535y := []int{4,5,6}
1536x = append(x, y...)
1537fmt.Println(x)
1538</pre>
1539Without that <code>...</code>, it wouldn't compile because the types
1540would be wrong; <code>y</code> is not of type <code>int</code>.
1541
Rob Pike6f89f3f2009-10-20 17:32:16 -07001542<h2 id="initialization">Initialization</h2>
1543
1544<p>
1545Although it doesn't look superficially very different from
1546initialization in C or C++, initialization in Go is more powerful.
1547Complex structures can be built during initialization and the ordering
1548issues between initialized objects in different packages are handled
1549correctly.
1550</p>
1551
1552<h3 id="constants">Constants</h3>
1553
1554<p>
1555Constants in Go are just that&mdash;constant.
1556They are created at compile time, even when defined as
1557locals in functions,
1558and can only be numbers, strings or booleans.
1559Because of the compile-time restriction, the expressions
1560that define them must be constant expressions,
1561evaluatable by the compiler. For instance,
1562<code>1&lt;&lt;3</code> is a constant expression, while
1563<code>math.Sin(math.Pi/4)</code> is not because
1564the function call to <code>math.Sin</code> needs
1565to happen at run time.
1566</p>
1567
1568<p>
1569In Go, enumerated constants are created using the <code>iota</code>
1570enumerator. Since <code>iota</code> can be part of an expression and
1571expressions can be implicitly repeated, it is easy to build intricate
1572sets of values.
Rob Pikebb3e3092009-10-31 18:29:06 -07001573</p>
Rob Pike6f89f3f2009-10-20 17:32:16 -07001574<pre>
1575type ByteSize float64
1576const (
Rob Pike163ecda2009-12-16 12:31:18 +11001577 _ = iota // ignore first value by assigning to blank identifier
Rob Pike77f6f162009-12-25 07:13:14 +11001578 KB ByteSize = 1&lt;&lt;(10*iota)
Rob Pike163ecda2009-12-16 12:31:18 +11001579 MB
1580 GB
1581 TB
1582 PB
Rob Pikec05f86a2010-01-04 07:36:39 +11001583 EB
1584 ZB
Rob Pike163ecda2009-12-16 12:31:18 +11001585 YB
Rob Pike6f89f3f2009-10-20 17:32:16 -07001586)
1587</pre>
1588<p>
1589The ability to attach a method such as <code>String</code> to a
1590type makes it possible for such values to format themselves
1591automatically for printing, even as part of a general type.
1592</p>
1593<pre>
1594func (b ByteSize) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001595 switch {
Rob Pike77f6f162009-12-25 07:13:14 +11001596 case b &gt;= YB:
James Fysh089ce172010-08-28 07:54:16 +10001597 return fmt.Sprintf("%.2fYB", float64(b/YB))
Rob Pikec05f86a2010-01-04 07:36:39 +11001598 case b &gt;= ZB:
James Fysh089ce172010-08-28 07:54:16 +10001599 return fmt.Sprintf("%.2fZB", float64(b/ZB))
Rob Pikec05f86a2010-01-04 07:36:39 +11001600 case b &gt;= EB:
James Fysh089ce172010-08-28 07:54:16 +10001601 return fmt.Sprintf("%.2fEB", float64(b/EB))
Rob Pike77f6f162009-12-25 07:13:14 +11001602 case b &gt;= PB:
James Fysh089ce172010-08-28 07:54:16 +10001603 return fmt.Sprintf("%.2fPB", float64(b/PB))
Rob Pike77f6f162009-12-25 07:13:14 +11001604 case b &gt;= TB:
James Fysh089ce172010-08-28 07:54:16 +10001605 return fmt.Sprintf("%.2fTB", float64(b/TB))
Rob Pike77f6f162009-12-25 07:13:14 +11001606 case b &gt;= GB:
James Fysh089ce172010-08-28 07:54:16 +10001607 return fmt.Sprintf("%.2fGB", float64(b/GB))
Rob Pike77f6f162009-12-25 07:13:14 +11001608 case b &gt;= MB:
James Fysh089ce172010-08-28 07:54:16 +10001609 return fmt.Sprintf("%.2fMB", float64(b/MB))
Rob Pike77f6f162009-12-25 07:13:14 +11001610 case b &gt;= KB:
James Fysh089ce172010-08-28 07:54:16 +10001611 return fmt.Sprintf("%.2fKB", float64(b/KB))
Rob Pike163ecda2009-12-16 12:31:18 +11001612 }
James Fysh089ce172010-08-28 07:54:16 +10001613 return fmt.Sprintf("%.2fB", float64(b))
Rob Pike6f89f3f2009-10-20 17:32:16 -07001614}
1615</pre>
1616<p>
James Fysh089ce172010-08-28 07:54:16 +10001617(The <code>float64</code> conversions prevent <code>Sprintf</code>
1618from recurring back through the <code>String</code> method for
1619<code>ByteSize</code>.)
Rob Pike6f89f3f2009-10-20 17:32:16 -07001620The expression <code>YB</code> prints as <code>1.00YB</code>,
Rob Pike49a35a62010-01-15 11:59:53 +11001621while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
Rob Pike6f89f3f2009-10-20 17:32:16 -07001622</p>
1623
1624<h3 id="variables">Variables</h3>
1625
1626<p>
1627Variables can be initialized just like constants but the
1628initializer can be a general expression computed at run time.
1629</p>
1630<pre>
1631var (
Rob Pike163ecda2009-12-16 12:31:18 +11001632 HOME = os.Getenv("HOME")
1633 USER = os.Getenv("USER")
1634 GOROOT = os.Getenv("GOROOT")
Rob Pike6f89f3f2009-10-20 17:32:16 -07001635)
1636</pre>
1637
1638<h3 id="init">The init function</h3>
1639
1640<p>
1641Finally, each source file can define its own <code>init()</code> function to
1642set up whatever state is required. The only restriction is that, although
1643goroutines can be launched during initialization, they will not begin
1644execution until it completes; initialization always runs as a single thread
1645of execution.
1646And finally means finally: <code>init()</code> is called after all the
1647variable declarations in the package have evaluated their initializers,
1648and those are evaluated only after all the imported packages have been
1649initialized.
1650</p>
1651<p>
1652Besides initializations that cannot be expressed as declarations,
1653a common use of <code>init()</code> functions is to verify or repair
1654correctness of the program state before real execution begins.
1655</p>
1656
1657<pre>
1658func init() {
Rob Pike163ecda2009-12-16 12:31:18 +11001659 if USER == "" {
Rob Pikeeea18d92011-02-01 12:47:35 -08001660 log.Fatal("$USER not set")
Rob Pike163ecda2009-12-16 12:31:18 +11001661 }
1662 if HOME == "" {
1663 HOME = "/usr/" + USER
1664 }
1665 if GOROOT == "" {
1666 GOROOT = HOME + "/go"
1667 }
1668 // GOROOT may be overridden by --goroot flag on command line.
1669 flag.StringVar(&amp;GOROOT, "goroot", GOROOT, "Go root directory")
Rob Pike6f89f3f2009-10-20 17:32:16 -07001670}
1671</pre>
1672
1673<h2 id="methods">Methods</h2>
Rob Pike2e5a1362009-09-27 17:59:36 -07001674
Rob Pike3e740792009-10-05 14:48:57 -07001675<h3 id="pointers_vs_values">Pointers vs. Values</h3>
1676<p>
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08001677Methods can be defined for any named type that is not a pointer or an interface;
Rob Pike3e740792009-10-05 14:48:57 -07001678the receiver does not have to be a struct.
1679<p>
1680In the discussion of slices above, we wrote an <code>Append</code>
1681function. We can define it as a method on slices instead. To do
1682this, we first declare a named type to which we can bind the method, and
1683then make the receiver for the method a value of that type.
1684</p>
1685<pre>
1686type ByteSlice []byte
1687
Rob Pikebcb46c82009-11-16 21:56:38 -08001688func (slice ByteSlice) Append(data []byte) []byte {
Rob Pike163ecda2009-12-16 12:31:18 +11001689 // Body exactly the same as above
Rob Pike3e740792009-10-05 14:48:57 -07001690}
1691</pre>
1692<p>
1693This still requires the method to return the updated slice. We can
1694eliminate that clumsiness by redefining the method to take a
1695<i>pointer</i> to a <code>ByteSlice</code> as its receiver, so the
1696method can overwrite the caller's slice.
1697</p>
1698<pre>
1699func (p *ByteSlice) Append(data []byte) {
Rob Pike163ecda2009-12-16 12:31:18 +11001700 slice := *p
1701 // Body as above, without the return.
1702 *p = slice
Rob Pike3e740792009-10-05 14:48:57 -07001703}
1704</pre>
1705<p>
1706In fact, we can do even better. If we modify our function so it looks
1707like a standard <code>Write</code> method, like this,
1708</p>
1709<pre>
1710func (p *ByteSlice) Write(data []byte) (n int, err os.Error) {
Rob Pike163ecda2009-12-16 12:31:18 +11001711 slice := *p
1712 // Again as above.
1713 *p = slice
1714 return len(data), nil
Rob Pike3e740792009-10-05 14:48:57 -07001715}
1716</pre>
1717<p>
1718then the type <code>*ByteSlice</code> satisfies the standard interface
1719<code>io.Writer</code>, which is handy. For instance, we can
Rob Pikeb95048f2009-10-13 14:32:21 -07001720print into one.
Rob Pike3e740792009-10-05 14:48:57 -07001721</p>
1722<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11001723 var b ByteSlice
1724 fmt.Fprintf(&amp;b, "This hour has %d days\n", 7)
Rob Pike3e740792009-10-05 14:48:57 -07001725</pre>
1726<p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001727We pass the address of a <code>ByteSlice</code>
Rob Pike3e740792009-10-05 14:48:57 -07001728because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>.
1729The rule about pointers vs. values for receivers is that value methods
1730can be invoked on pointers and values, but pointer methods can only be
1731invoked on pointers. This is because pointer methods can modify the
1732receiver; invoking them on a copy of the value would cause those
1733modifications to be discarded.
1734</p>
1735<p>
1736By the way, the idea of using <code>Write</code> on a slice of bytes
1737is implemented by <code>bytes.Buffer</code>.
1738</p>
Rob Pike2e5a1362009-09-27 17:59:36 -07001739
Rob Pike2119b362009-10-14 23:03:08 -07001740<h2 id="interfaces_and_types">Interfaces and other types</h2>
Rob Pike8aec6122009-09-02 16:41:41 -07001741
Rob Pikeb95048f2009-10-13 14:32:21 -07001742<h3 id="interfaces">Interfaces</h3>
1743<p>
1744Interfaces in Go provide a way to specify the behavior of an
1745object: if something can do <em>this</em>, then it can be used
1746<em>here</em>. We've seen a couple of simple examples already;
1747custom printers can be implemented by a <code>String</code> method
1748while <code>Fprintf</code> can generate output to anything
1749with a <code>Write</code> method.
Rob Pike2119b362009-10-14 23:03:08 -07001750Interfaces with only one or two methods are common in Go code, and are
Rob Pikeb95048f2009-10-13 14:32:21 -07001751usually given a name derived from the method, such as <code>io.Writer</code>
1752for something that implements <code>Write</code>.
1753</p>
1754<p>
1755A type can implement multiple interfaces.
1756For instance, a collection can be sorted
1757by the routines in package <code>sort</code> if it implements
1758<code>sort.Interface</code>, which contains <code>Len()</code>,
Russ Cox24ce19c2009-11-08 01:07:53 -08001759<code>Less(i, j int) bool</code>, and <code>Swap(i, j int)</code>,
Rob Pikeb95048f2009-10-13 14:32:21 -07001760and it could also have a custom formatter.
1761In this contrived example <code>Sequence</code> satisfies both.
1762</p>
1763<pre>
1764type Sequence []int
Russ Cox94439982009-06-25 09:38:35 -07001765
Rob Pikeb95048f2009-10-13 14:32:21 -07001766// Methods required by sort.Interface.
1767func (s Sequence) Len() int {
Rob Pike163ecda2009-12-16 12:31:18 +11001768 return len(s)
Rob Pikeb95048f2009-10-13 14:32:21 -07001769}
1770func (s Sequence) Less(i, j int) bool {
Rob Pike77f6f162009-12-25 07:13:14 +11001771 return s[i] &lt; s[j]
Rob Pikeb95048f2009-10-13 14:32:21 -07001772}
1773func (s Sequence) Swap(i, j int) {
Rob Pike163ecda2009-12-16 12:31:18 +11001774 s[i], s[j] = s[j], s[i]
Rob Pikeb95048f2009-10-13 14:32:21 -07001775}
Russ Cox94439982009-06-25 09:38:35 -07001776
Rob Pikeb95048f2009-10-13 14:32:21 -07001777// Method for printing - sorts the elements before printing.
1778func (s Sequence) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001779 sort.Sort(s)
1780 str := "["
1781 for i, elem := range s {
Rob Pike77f6f162009-12-25 07:13:14 +11001782 if i &gt; 0 {
Rob Pike163ecda2009-12-16 12:31:18 +11001783 str += " "
1784 }
1785 str += fmt.Sprint(elem)
1786 }
1787 return str + "]"
Rob Pikeb95048f2009-10-13 14:32:21 -07001788}
1789</pre>
Russ Cox94439982009-06-25 09:38:35 -07001790
Rob Pikeb95048f2009-10-13 14:32:21 -07001791<h3 id="conversions">Conversions</h3>
1792
1793<p>
1794The <code>String</code> method of <code>Sequence</code> is recreating the
1795work that <code>Sprint</code> already does for slices. We can share the
1796effort if we convert the <code>Sequence</code> to a plain
1797<code>[]int</code> before calling <code>Sprint</code>.
1798</p>
1799<pre>
1800func (s Sequence) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001801 sort.Sort(s)
1802 return fmt.Sprint([]int(s))
Rob Pikeb95048f2009-10-13 14:32:21 -07001803}
1804</pre>
1805<p>
1806The conversion causes <code>s</code> to be treated as an ordinary slice
1807and therefore receive the default formatting.
1808Without the conversion, <code>Sprint</code> would find the
1809<code>String</code> method of <code>Sequence</code> and recur indefinitely.
1810Because the two types (<code>Sequence</code> and <code>[]int</code>)
1811are the same if we ignore the type name, it's legal to convert between them.
1812The conversion doesn't create a new value, it just temporarily acts
1813as though the existing value has a new type.
Rob Pike80e25fc2011-01-19 23:07:38 -05001814(There are other legal conversions, such as from integer to floating point, that
Rob Pikeb95048f2009-10-13 14:32:21 -07001815do create a new value.)
1816</p>
1817<p>
Rob Pikec2b64182009-11-01 20:54:11 -08001818It's an idiom in Go programs to convert the
Rob Pikeb95048f2009-10-13 14:32:21 -07001819type of an expression to access a different
1820set of methods. As an example, we could use the existing
1821type <code>sort.IntArray</code> to reduce the entire example
1822to this:
1823</p>
1824<pre>
1825type Sequence []int
1826
1827// Method for printing - sorts the elements before printing
1828func (s Sequence) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11001829 sort.IntArray(s).Sort()
1830 return fmt.Sprint([]int(s))
Rob Pikeb95048f2009-10-13 14:32:21 -07001831}
1832</pre>
1833<p>
1834Now, instead of having <code>Sequence</code> implement multiple
1835interfaces (sorting and printing), we're using the ability of a data item to be
1836converted to multiple types (<code>Sequence</code>, <code>sort.IntArray</code>
1837and <code>[]int</code>), each of which does some part of the job.
1838That's more unusual in practice but can be effective.
1839</p>
1840
1841<h3 id="generality">Generality</h3>
Russ Cox94439982009-06-25 09:38:35 -07001842<p>
1843If a type exists only to implement an interface
1844and has no exported methods beyond that interface,
Rob Pike2119b362009-10-14 23:03:08 -07001845there is no need to export the type itself.
1846Exporting just the interface makes it clear that
1847it's the behavior that matters, not the implementation,
1848and that other implementations with different properties
1849can mirror the behavior of the original type.
Rob Pikeb95048f2009-10-13 14:32:21 -07001850It also avoids the need to repeat the documentation
1851on every instance of a common method.
Russ Cox94439982009-06-25 09:38:35 -07001852</p>
Russ Cox94439982009-06-25 09:38:35 -07001853<p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001854In such cases, the constructor should return an interface value
1855rather than the implementing type.
1856As an example, in the hash libraries
1857both <code>crc32.NewIEEE()</code> and <code>adler32.New()</code>
1858return the interface type <code>hash.Hash32</code>.
Russ Cox94439982009-06-25 09:38:35 -07001859Substituting the CRC-32 algorithm for Adler-32 in a Go program
Rob Pikeb95048f2009-10-13 14:32:21 -07001860requires only changing the constructor call;
Rob Pikeeaf6a342009-07-06 15:15:56 -07001861the rest of the code is unaffected by the change of algorithm.
Russ Cox94439982009-06-25 09:38:35 -07001862</p>
Rob Pikeb95048f2009-10-13 14:32:21 -07001863<p>
1864A similar approach allows the streaming cipher algorithms
1865in the <code>crypto/block</code> package to be
1866separated from the block ciphers they chain together.
Rob Pikec2b64182009-11-01 20:54:11 -08001867By analogy with the <code>bufio</code> package,
Rob Pikeb95048f2009-10-13 14:32:21 -07001868they wrap a <code>Cipher</code> interface
Rob Pikec2b64182009-11-01 20:54:11 -08001869and return <code>hash.Hash</code>,
Rob Pikeb95048f2009-10-13 14:32:21 -07001870<code>io.Reader</code>, or <code>io.Writer</code>
Rob Pike2119b362009-10-14 23:03:08 -07001871interface values, not specific implementations.
Rob Pikeb95048f2009-10-13 14:32:21 -07001872</p>
1873<p>
1874The interface to <code>crypto/block</code> includes:
1875</p>
1876<pre>
1877type Cipher interface {
Rob Pike163ecda2009-12-16 12:31:18 +11001878 BlockSize() int
1879 Encrypt(src, dst []byte)
1880 Decrypt(src, dst []byte)
Rob Pikeb95048f2009-10-13 14:32:21 -07001881}
Russ Cox94439982009-06-25 09:38:35 -07001882
Rob Pikeb95048f2009-10-13 14:32:21 -07001883// NewECBDecrypter returns a reader that reads data
1884// from r and decrypts it using c in electronic codebook (ECB) mode.
1885func NewECBDecrypter(c Cipher, r io.Reader) io.Reader
Russ Cox94439982009-06-25 09:38:35 -07001886
Rob Pikeb95048f2009-10-13 14:32:21 -07001887// NewCBCDecrypter returns a reader that reads data
1888// from r and decrypts it using c in cipher block chaining (CBC) mode
1889// with the initialization vector iv.
1890func NewCBCDecrypter(c Cipher, iv []byte, r io.Reader) io.Reader
1891</pre>
1892<p>
1893<code>NewECBDecrypter</code> and <code>NewCBCReader</code> apply not
1894just to one specific encryption algorithm and data source but to any
1895implementation of the <code>Cipher</code> interface and any
1896<code>io.Reader</code>. Because they return <code>io.Reader</code>
1897interface values, replacing ECB
1898encryption with CBC encryption is a localized change. The constructor
Russ Cox24ce19c2009-11-08 01:07:53 -08001899calls must be edited, but because the surrounding code must treat the result only
Rob Pikeb95048f2009-10-13 14:32:21 -07001900as an <code>io.Reader</code>, it won't notice the difference.
1901</p>
Rob Piked2228692009-10-12 21:18:23 -07001902
Rob Pike2119b362009-10-14 23:03:08 -07001903<h3 id="interface_methods">Interfaces and methods</h3>
1904<p>
1905Since almost anything can have methods attached, almost anything can
1906satisfy an interface. One illustrative example is in the <code>http</code>
1907package, which defines the <code>Handler</code> interface. Any object
1908that implements <code>Handler</code> can serve HTTP requests.
1909</p>
1910<pre>
1911type Handler interface {
Rob Pike1edfb4c2010-09-29 11:12:52 -07001912 ServeHTTP(ResponseWriter, *Request)
Rob Pike2119b362009-10-14 23:03:08 -07001913}
1914</pre>
1915<p>
Rob Pike1edfb4c2010-09-29 11:12:52 -07001916<code>ResponseWriter</code> is itself an interface that provides access
1917to the methods needed to return the response to the client.
1918Those methods include the standard <code>Write</code> method, so an
1919<code>http.ResponseWriter</code> can be used wherever an <code>io.Writer</code>
1920can be used.
1921<code>Request</code> is a struct containing a parsed representation
1922of the request from the client.
1923<p>
Rob Pike2119b362009-10-14 23:03:08 -07001924For brevity, let's ignore POSTs and assume HTTP requests are always
1925GETs; that simplification does not affect the way the handlers are
Rob Pike88407262009-10-16 11:13:40 -07001926set up. Here's a trivial but complete implementation of a handler to
Rob Pike2119b362009-10-14 23:03:08 -07001927count the number of times the
1928page is visited.
1929</p>
1930<pre>
1931// Simple counter server.
1932type Counter struct {
Rob Pike163ecda2009-12-16 12:31:18 +11001933 n int
Rob Pike2119b362009-10-14 23:03:08 -07001934}
1935
Rob Pike1edfb4c2010-09-29 11:12:52 -07001936func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11001937 ctr.n++
Rob Pike1edfb4c2010-09-29 11:12:52 -07001938 fmt.Fprintf(w, "counter = %d\n", ctr.n)
Rob Pike2119b362009-10-14 23:03:08 -07001939}
1940</pre>
1941<p>
Rob Pike1edfb4c2010-09-29 11:12:52 -07001942(Keeping with our theme, note how <code>Fprintf</code> can print to an
1943<code>http.ResponseWriter</code>.)
Rob Pike88407262009-10-16 11:13:40 -07001944For reference, here's how to attach such a server to a node on the URL tree.
Rob Pike2119b362009-10-14 23:03:08 -07001945<pre>
1946import "http"
1947...
Rob Pike163ecda2009-12-16 12:31:18 +11001948ctr := new(Counter)
1949http.Handle("/counter", ctr)
Rob Pike2119b362009-10-14 23:03:08 -07001950</pre>
1951<p>
1952But why make <code>Counter</code> a struct? An integer is all that's needed.
1953(The receiver needs to be a pointer so the increment is visible to the caller.)
1954</p>
1955<pre>
1956// Simpler counter server.
1957type Counter int
1958
Rob Pike1edfb4c2010-09-29 11:12:52 -07001959func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11001960 *ctr++
Rob Pike1edfb4c2010-09-29 11:12:52 -07001961 fmt.Fprintf(w, "counter = %d\n", *ctr)
Rob Pike2119b362009-10-14 23:03:08 -07001962}
1963</pre>
1964<p>
1965What if your program has some internal state that needs to be notified that a page
1966has been visited? Tie a channel to the web page.
1967</p>
1968<pre>
1969// A channel that sends a notification on each visit.
1970// (Probably want the channel to be buffered.)
Rob Pike88407262009-10-16 11:13:40 -07001971type Chan chan *http.Request
Rob Pike2119b362009-10-14 23:03:08 -07001972
Rob Pike1edfb4c2010-09-29 11:12:52 -07001973func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Rob Pike77f6f162009-12-25 07:13:14 +11001974 ch &lt;- req
Rob Pike1edfb4c2010-09-29 11:12:52 -07001975 fmt.Fprint(w, "notification sent")
Rob Pike2119b362009-10-14 23:03:08 -07001976}
1977</pre>
1978<p>
1979Finally, let's say we wanted to present on <code>/args</code> the arguments
1980used when invoking the server binary.
Rob Pike88407262009-10-16 11:13:40 -07001981It's easy to write a function to print the arguments.
Rob Pike2119b362009-10-14 23:03:08 -07001982</p>
1983<pre>
1984func ArgServer() {
Rob Pike163ecda2009-12-16 12:31:18 +11001985 for i, s := range os.Args {
1986 fmt.Println(s)
1987 }
Rob Pike2119b362009-10-14 23:03:08 -07001988}
1989</pre>
1990<p>
1991How do we turn that into an HTTP server? We could make <code>ArgServer</code>
1992a method of some type whose value we ignore, but there's a cleaner way.
Rob Pike88407262009-10-16 11:13:40 -07001993Since we can define a method for any type except pointers and interfaces,
1994we can write a method for a function.
Rob Pike2119b362009-10-14 23:03:08 -07001995The <code>http</code> package contains this code:
1996</p>
1997<pre>
1998// The HandlerFunc type is an adapter to allow the use of
1999// ordinary functions as HTTP handlers. If f is a function
2000// with the appropriate signature, HandlerFunc(f) is a
2001// Handler object that calls f.
Rob Pike1edfb4c2010-09-29 11:12:52 -07002002type HandlerFunc func(ResponseWriter, *Request)
Rob Pike2119b362009-10-14 23:03:08 -07002003
2004// ServeHTTP calls f(c, req).
Rob Pike1edfb4c2010-09-29 11:12:52 -07002005func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) {
2006 f(w, req)
Rob Pike2119b362009-10-14 23:03:08 -07002007}
2008</pre>
2009<p>
2010<code>HandlerFunc</code> is a type with a method, <code>ServeHTTP</code>,
2011so values of that type can serve HTTP requests. Look at the implementation
2012of the method: the receiver is a function, <code>f</code>, and the method
Rob Pikec2b64182009-11-01 20:54:11 -08002013calls <code>f</code>. That may seem odd but it's not that different from, say,
Rob Pike2119b362009-10-14 23:03:08 -07002014the receiver being a channel and the method sending on the channel.
2015</p>
2016<p>
Rob Pike88407262009-10-16 11:13:40 -07002017To make <code>ArgServer</code> into an HTTP server, we first modify it
2018to have the right signature.
Rob Pike2119b362009-10-14 23:03:08 -07002019</p>
2020<pre>
2021// Argument server.
Rob Pike1edfb4c2010-09-29 11:12:52 -07002022func ArgServer(w http.ResponseWriter, req *http.Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002023 for i, s := range os.Args {
Rob Pike1edfb4c2010-09-29 11:12:52 -07002024 fmt.Fprintln(w, s)
Rob Pike163ecda2009-12-16 12:31:18 +11002025 }
Rob Pike2119b362009-10-14 23:03:08 -07002026}
2027</pre>
2028<p>
Rob Pike88407262009-10-16 11:13:40 -07002029<code>ArgServer</code> now has same signature as <code>HandlerFunc</code>,
2030so it can be converted to that type to access its methods,
2031just as we converted <code>Sequence</code> to <code>IntArray</code>
2032to access <code>IntArray.Sort</code>.
2033The code to set it up is concise:
Rob Pike2119b362009-10-14 23:03:08 -07002034</p>
2035<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002036http.Handle("/args", http.HandlerFunc(ArgServer))
Rob Pike2119b362009-10-14 23:03:08 -07002037</pre>
2038<p>
2039When someone visits the page <code>/args</code>,
Rob Pike88407262009-10-16 11:13:40 -07002040the handler installed at that page has value <code>ArgServer</code>
2041and type <code>HandlerFunc</code>.
Rob Pike2119b362009-10-14 23:03:08 -07002042The HTTP server will invoke the method <code>ServeHTTP</code>
Rob Pike88407262009-10-16 11:13:40 -07002043of that type, with <code>ArgServer</code> as the receiver, which will in turn call
Rob Pike2119b362009-10-14 23:03:08 -07002044<code>ArgServer</code> (via the invocation <code>f(c, req)</code>
Rob Pike88407262009-10-16 11:13:40 -07002045inside <code>HandlerFunc.ServeHTTP</code>).
2046The arguments will then be displayed.
Rob Pike2119b362009-10-14 23:03:08 -07002047</p>
2048<p>
Rob Pike88407262009-10-16 11:13:40 -07002049In this section we have made an HTTP server from a struct, an integer,
Rob Pike2119b362009-10-14 23:03:08 -07002050a channel, and a function, all because interfaces are just sets of
2051methods, which can be defined for (almost) any type.
2052</p>
2053
Rob Pike88407262009-10-16 11:13:40 -07002054<h2 id="embedding">Embedding</h2>
2055
2056<p>
2057Go does not provide the typical, type-driven notion of subclassing,
2058but it does have the ability to &ldquo;borrow&rdquo; pieces of an
2059implementation by <em>embedding</em> types within a struct or
2060interface.
2061</p>
2062<p>
2063Interface embedding is very simple.
2064We've mentioned the <code>io.Reader</code> and <code>io.Writer</code> interfaces before;
2065here are their definitions.
2066</p>
2067<pre>
2068type Reader interface {
Rob Pike163ecda2009-12-16 12:31:18 +11002069 Read(p []byte) (n int, err os.Error)
Rob Pike88407262009-10-16 11:13:40 -07002070}
2071
2072type Writer interface {
Rob Pike163ecda2009-12-16 12:31:18 +11002073 Write(p []byte) (n int, err os.Error)
Rob Pike88407262009-10-16 11:13:40 -07002074}
2075</pre>
2076<p>
2077The <code>io</code> package also exports several other interfaces
2078that specify objects that can implement several such methods.
2079For instance, there is <code>io.ReadWriter</code>, an interface
2080containing both <code>Read</code> and <code>Write</code>.
2081We could specify <code>io.ReadWriter</code> by listing the
2082two methods explicitly, but it's easier and more evocative
2083to embed the two interfaces to form the new one, like this:
2084</p>
2085<pre>
Rob Pike7ddbe792010-08-24 12:37:51 +10002086// ReadWriter is the interface that combines the Reader and Writer interfaces.
Rob Pike88407262009-10-16 11:13:40 -07002087type ReadWriter interface {
Rob Pike163ecda2009-12-16 12:31:18 +11002088 Reader
2089 Writer
Rob Pike88407262009-10-16 11:13:40 -07002090}
2091</pre>
2092<p>
2093This says just what it looks like: A <code>ReadWriter</code> can do
2094what a <code>Reader</code> does <em>and</em> what a <code>Writer</code>
2095does; it is a union of the embedded interfaces (which must be disjoint
2096sets of methods).
2097Only interfaces can be embedded within interfaces.
2098<p>
2099The same basic idea applies to structs, but with more far-reaching
2100implications. The <code>bufio</code> package has two struct types,
2101<code>bufio.Reader</code> and <code>bufio.Writer</code>, each of
2102which of course implements the analogous interfaces from package
2103<code>io</code>.
2104And <code>bufio</code> also implements a buffered reader/writer,
2105which it does by combining a reader and a writer into one struct
2106using embedding: it lists the types within the struct
2107but does not give them field names.
2108</p>
2109<pre>
2110// ReadWriter stores pointers to a Reader and a Writer.
2111// It implements io.ReadWriter.
2112type ReadWriter struct {
Rob Pike49a35a62010-01-15 11:59:53 +11002113 *Reader // *bufio.Reader
2114 *Writer // *bufio.Writer
Rob Pike88407262009-10-16 11:13:40 -07002115}
2116</pre>
2117<p>
Rob Pike49a35a62010-01-15 11:59:53 +11002118The embedded elements are pointers to structs and of course
2119must be initialized to point to valid structs before they
2120can be used.
2121The <code>ReadWriter</code> struct could be written as
Rob Pike88407262009-10-16 11:13:40 -07002122</p>
2123<pre>
2124type ReadWriter struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002125 reader *Reader
2126 writer *Writer
Rob Pike88407262009-10-16 11:13:40 -07002127}
2128</pre>
2129<p>
2130but then to promote the methods of the fields and to
2131satisfy the <code>io</code> interfaces, we would also need
2132to provide forwarding methods, like this:
2133</p>
2134<pre>
2135func (rw *ReadWriter) Read(p []byte) (n int, err os.Error) {
Rob Pike163ecda2009-12-16 12:31:18 +11002136 return rw.reader.Read(p)
Rob Pike88407262009-10-16 11:13:40 -07002137}
2138</pre>
2139<p>
2140By embedding the structs directly, we avoid this bookkeeping.
2141The methods of embedded types come along for free, which means that <code>bufio.ReadWriter</code>
2142not only has the methods of <code>bufio.Reader</code> and <code>bufio.Writer</code>,
2143it also satisfies all three interfaces:
2144<code>io.Reader</code>,
2145<code>io.Writer</code>, and
2146<code>io.ReadWriter</code>.
2147</p>
2148<p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002149There's an important way in which embedding differs from subclassing. When we embed a type,
Rob Pikec58d9ef2009-10-16 11:23:45 -07002150the methods of that type become methods of the outer type,
2151but when they are invoked the receiver of the method is the inner type, not the outer one.
Rob Pike88407262009-10-16 11:13:40 -07002152In our example, when the <code>Read</code> method of a <code>bufio.ReadWriter</code> is
Rob Pikef00be0c2009-10-16 16:16:02 -07002153invoked, it has exactly the same effect as the forwarding method written out above;
Rob Pike88407262009-10-16 11:13:40 -07002154the receiver is the <code>reader</code> field of the <code>ReadWriter</code>, not the
2155<code>ReadWriter</code> itself.
2156</p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002157<p>
2158Embedding can also be a simple convenience.
2159This example shows an embedded field alongside a regular, named field.
2160</p>
2161<pre>
2162type Job struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002163 Command string
2164 *log.Logger
Rob Pikef00be0c2009-10-16 16:16:02 -07002165}
2166</pre>
2167<p>
2168The <code>Job</code> type now has the <code>Log</code>, <code>Logf</code>
2169and other
Rob Pike6c088592010-06-14 22:40:35 -07002170methods of <code>*log.Logger</code>. We could have given the <code>Logger</code>
Rob Pike49a35a62010-01-15 11:59:53 +11002171a field name, of course, but it's not necessary to do so. And now, once
2172initialized, we can
2173log to the <code>Job</code>:
Rob Pikef00be0c2009-10-16 16:16:02 -07002174</p>
2175<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002176job.Log("starting now...")
Rob Pikef00be0c2009-10-16 16:16:02 -07002177</pre>
2178<p>
Rob Pike9f60b032009-10-19 10:34:00 -07002179The <code>Logger</code> is a regular field of the struct and we can initialize
Rob Pike49a35a62010-01-15 11:59:53 +11002180it in the usual way with a constructor,
Rob Pike9f60b032009-10-19 10:34:00 -07002181</p>
2182<pre>
2183func NewJob(command string, logger *log.Logger) *Job {
Rob Pike163ecda2009-12-16 12:31:18 +11002184 return &amp;Job{command, logger}
Rob Pike9f60b032009-10-19 10:34:00 -07002185}
2186</pre>
2187<p>
Rob Pike49a35a62010-01-15 11:59:53 +11002188or with a composite literal,
2189</p>
2190<pre>
Rob Pikee787f8272010-10-12 16:56:50 -07002191job := &amp;Job{command, log.New(os.Stderr, "Job: ", log.Ldate)}
Rob Pike49a35a62010-01-15 11:59:53 +11002192</pre>
2193<p>
Rob Pikef00be0c2009-10-16 16:16:02 -07002194If we need to refer to an embedded field directly, the type name of the field,
2195ignoring the package qualifier, serves as a field name. If we needed to access the
2196<code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>,
2197we would write <code>job.Logger</code>.
2198This would be useful if we wanted to refine the methods of <code>Logger</code>.
2199</p>
2200<pre>
Rob Pike9f60b032009-10-19 10:34:00 -07002201func (job *Job) Logf(format string, args ...) {
Rob Pike163ecda2009-12-16 12:31:18 +11002202 job.Logger.Logf("%q: %s", job.Command, fmt.Sprintf(format, args))
Rob Pikef00be0c2009-10-16 16:16:02 -07002203}
2204</pre>
2205<p>
2206Embedding types introduces the problem of name conflicts but the rules to resolve
2207them are simple.
2208First, a field or method <code>X</code> hides any other item <code>X</code> in a more deeply
2209nested part of the type.
2210If <code>log.Logger</code> contained a field or method called <code>Command</code>, the <code>Command</code> field
2211of <code>Job</code> would dominate it.
2212</p>
2213<p>
2214Second, if the same name appears at the same nesting level, it is usually an error;
Rob Pike6c088592010-06-14 22:40:35 -07002215it would be erroneous to embed <code>log.Logger</code> if the <code>Job</code> struct
Rob Pikef00be0c2009-10-16 16:16:02 -07002216contained another field or method called <code>Logger</code>.
2217However, if the duplicate name is never mentioned in the program outside the type definition, it is OK.
2218This qualification provides some protection against changes made to types embedded from outside; there
Rob Pikec2b64182009-11-01 20:54:11 -08002219is no problem if a field is added that conflicts with another field in another subtype if neither field
2220is ever used.
Rob Pikef00be0c2009-10-16 16:16:02 -07002221</p>
Rob Pike88407262009-10-16 11:13:40 -07002222
2223
Rob Pike430d4622009-10-20 12:30:39 -07002224<h2 id="concurrency">Concurrency</h2>
2225
2226<h3 id="sharing">Share by communicating</h3>
2227
2228<p>
Rob Pikebb3e3092009-10-31 18:29:06 -07002229Concurrent programming is a large topic and there is space only for some
2230Go-specific highlights here.
2231</p>
2232<p>
Rob Pike430d4622009-10-20 12:30:39 -07002233Concurrent programming in many environments is made difficult by the
2234subtleties required to implement correct access to shared variables. Go encourages
2235a different approach in which shared values are passed around on channels
2236and, in fact, never actively shared by separate threads of execution.
2237Only one goroutine has access to the value at any given time.
2238Data races cannot occur, by design.
2239To encourage this way of thinking we have reduced it to a slogan:
2240</p>
2241<blockquote>
2242Do not communicate by sharing memory;
2243instead, share memory by communicating.
2244</blockquote>
2245<p>
2246This approach can be taken too far. Reference counts may be best done
2247by putting a mutex around an integer variable, for instance. But as a
2248high-level approach, using channels to control access makes it easier
2249to write clear, correct programs.
2250</p>
2251<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002252One way to think about this model is to consider a typical single-threaded
Rob Pike430d4622009-10-20 12:30:39 -07002253program running on one CPU. It has no need for synchronization primitives.
2254Now run another such instance; it too needs no synchronization. Now let those
2255two communicate; if the communication is the synchronizer, there's still no need
Rob Pikec2b64182009-11-01 20:54:11 -08002256for other synchronization. Unix pipelines, for example, fit this model
Rob Pikebb3e3092009-10-31 18:29:06 -07002257perfectly. Although Go's approach to concurrency originates in Hoare's
Rob Pike430d4622009-10-20 12:30:39 -07002258Communicating Sequential Processes (CSP),
2259it can also be seen as a type-safe generalization of Unix pipes.
2260</p>
2261
2262<h3 id="goroutines">Goroutines</h3>
2263
Rob Pikebb3e3092009-10-31 18:29:06 -07002264<p>
2265They're called <em>goroutines</em> because the existing
2266terms&mdash;threads, coroutines, processes, and so on&mdash;convey
2267inaccurate connotations. A goroutine has a simple model: it is a
2268function executing in parallel with other goroutines in the same
2269address space. It is lightweight, costing little more than the
2270allocation of stack space.
2271And the stacks start small, so they are cheap, and grow
2272by allocating (and freeing) heap storage as required.
2273</p>
2274<p>
2275Goroutines are multiplexed onto multiple OS threads so if one should
2276block, such as while waiting for I/O, others continue to run. Their
2277design hides many of the complexities of thread creation and
2278management.
2279</p>
2280<p>
2281Prefix a function or method call with the <code>go</code>
2282keyword to run the call in a new goroutine.
2283When the call completes, the goroutine
2284exits, silently. (The effect is similar to the Unix shell's
2285<code>&amp;</code> notation for running a command in the
2286background.)
2287</p>
2288<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002289go list.Sort() // run list.Sort in parallel; don't wait for it.
Rob Pikebb3e3092009-10-31 18:29:06 -07002290</pre>
2291<p>
2292A function literal can be handy in a goroutine invocation.
2293<pre>
2294func Announce(message string, delay int64) {
Rob Pike163ecda2009-12-16 12:31:18 +11002295 go func() {
2296 time.Sleep(delay)
2297 fmt.Println(message)
2298 }() // Note the parentheses - must call the function.
Rob Pikebb3e3092009-10-31 18:29:06 -07002299}
2300</pre>
2301<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002302In Go, function literals are closures: the implementation makes
Rob Pikebb3e3092009-10-31 18:29:06 -07002303sure the variables referred to by the function survive as long as they are active.
2304<p>
2305These examples aren't too practical because the functions have no way of signaling
2306completion. For that, we need channels.
2307</p>
2308
Rob Pike430d4622009-10-20 12:30:39 -07002309<h3 id="channels">Channels</h3>
2310
Rob Pikebb3e3092009-10-31 18:29:06 -07002311<p>
2312Like maps, channels are a reference type and are allocated with <code>make</code>.
2313If an optional integer parameter is provided, it sets the buffer size for the channel.
2314The default is zero, for an unbuffered or synchronous channel.
2315</p>
2316<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002317ci := make(chan int) // unbuffered channel of integers
2318cj := make(chan int, 0) // unbuffered channel of integers
2319cs := make(chan *os.File, 100) // buffered channel of pointers to Files
Rob Pikebb3e3092009-10-31 18:29:06 -07002320</pre>
2321<p>
2322Channels combine communication&mdash;the exchange of a value&mdash;with
2323synchronization&mdash;guaranteeing that two calculations (goroutines) are in
2324a known state.
2325</p>
2326<p>
2327There are lots of nice idioms using channels. Here's one to get us started.
2328In the previous section we launched a sort in the background. A channel
2329can allow the launching goroutine to wait for the sort to complete.
2330</p>
2331<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002332c := make(chan int) // Allocate a channel.
Rob Pikebb3e3092009-10-31 18:29:06 -07002333// Start the sort in a goroutine; when it completes, signal on the channel.
2334go func() {
Rob Pike163ecda2009-12-16 12:31:18 +11002335 list.Sort()
2336 c &lt;- 1 // Send a signal; value does not matter.
2337}()
2338doSomethingForAWhile()
2339&lt;-c // Wait for sort to finish; discard sent value.
Rob Pikebb3e3092009-10-31 18:29:06 -07002340</pre>
2341<p>
2342Receivers always block until there is data to receive.
2343If the channel is unbuffered, the sender blocks until the receiver has
2344received the value.
2345If the channel has a buffer, the sender blocks only until the
Ian Lance Taylorcc6720a2009-11-10 00:09:53 -08002346value has been copied to the buffer; if the buffer is full, this
2347means waiting until some receiver has retrieved a value.
Rob Pikebb3e3092009-10-31 18:29:06 -07002348</p>
2349<p>
2350A buffered channel can be used like a semaphore, for instance to
2351limit throughput. In this example, incoming requests are passed
2352to <code>handle</code>, which sends a value into the channel, processes
Rob Pikec2b64182009-11-01 20:54:11 -08002353the request, and then receives a value from the channel.
Rob Pikebb3e3092009-10-31 18:29:06 -07002354The capacity of the channel buffer limits the number of
2355simultaneous calls to <code>process</code>.
2356</p>
2357<pre>
2358var sem = make(chan int, MaxOutstanding)
2359
2360func handle(r *Request) {
Rob Pike77f6f162009-12-25 07:13:14 +11002361 sem &lt;- 1 // Wait for active queue to drain.
Rob Pike163ecda2009-12-16 12:31:18 +11002362 process(r) // May take a long time.
Rob Pike77f6f162009-12-25 07:13:14 +11002363 &lt;-sem // Done; enable next request to run.
Rob Pikebb3e3092009-10-31 18:29:06 -07002364}
2365
2366func Serve(queue chan *Request) {
2367 for {
Rob Pike77f6f162009-12-25 07:13:14 +11002368 req := &lt;-queue
Rob Pike163ecda2009-12-16 12:31:18 +11002369 go handle(req) // Don't wait for handle to finish.
Rob Pikebb3e3092009-10-31 18:29:06 -07002370 }
2371}
2372</pre>
2373<p>
2374Here's the same idea implemented by starting a fixed
2375number of <code>handle</code> goroutines all reading from the request
2376channel.
2377The number of goroutines limits the number of simultaneous
2378calls to <code>process</code>.
2379This <code>Serve</code> function also accepts a channel on which
2380it will be told to exit; after launching the goroutines it blocks
2381receiving from that channel.
2382</p>
2383<pre>
2384func handle(queue chan *Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002385 for r := range queue {
2386 process(r)
2387 }
Rob Pikebb3e3092009-10-31 18:29:06 -07002388}
2389
2390func Serve(clientRequests chan *clientRequests, quit chan bool) {
Rob Pike163ecda2009-12-16 12:31:18 +11002391 // Start handlers
Rob Pike77f6f162009-12-25 07:13:14 +11002392 for i := 0; i &lt; MaxOutstanding; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11002393 go handle(clientRequests)
2394 }
Rob Pike77f6f162009-12-25 07:13:14 +11002395 &lt;-quit // Wait to be told to exit.
Rob Pikebb3e3092009-10-31 18:29:06 -07002396}
2397</pre>
2398
2399<h3 id="chan_of_chan">Channels of channels</h3>
2400<p>
2401One of the most important properties of Go is that
2402a channel is a first-class value that can be allocated and passed
2403around like any other. A common use of this property is
2404to implement safe, parallel demultiplexing.
2405<p>
2406In the example in the previous section, <code>handle</code> was
2407an idealized handler for a request but we didn't define the
2408type it was handling. If that type includes a channel on which
2409to reply, each client can provide its own path for the answer.
2410Here's a schematic definition of type <code>Request</code>.
2411</p>
2412<pre>
2413type Request struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002414 args []int
2415 f func([]int) int
2416 resultChan chan int
Rob Pikebb3e3092009-10-31 18:29:06 -07002417}
2418</pre>
2419<p>
2420The client provides a function and its arguments, as well as
2421a channel inside the request object on which to receive the answer.
2422</p>
2423<pre>
2424func sum(a []int) (s int) {
Rob Pike163ecda2009-12-16 12:31:18 +11002425 for _, v := range a {
2426 s += v
2427 }
2428 return
Rob Pikebb3e3092009-10-31 18:29:06 -07002429}
2430
2431request := &amp;Request{[]int{3, 4, 5}, sum, make(chan int)}
2432// Send request
Rob Pike77f6f162009-12-25 07:13:14 +11002433clientRequests &lt;- request
Rob Pikebb3e3092009-10-31 18:29:06 -07002434// Wait for response.
Rob Pike77f6f162009-12-25 07:13:14 +11002435fmt.Printf("answer: %d\n", &lt;-request.resultChan)
Rob Pikebb3e3092009-10-31 18:29:06 -07002436</pre>
2437<p>
2438On the server side, the handler function is the only thing that changes.
2439</p>
2440<pre>
2441func handle(queue chan *Request) {
Rob Pike163ecda2009-12-16 12:31:18 +11002442 for req := range queue {
Rob Pike77f6f162009-12-25 07:13:14 +11002443 req.resultChan &lt;- req.f(req.args)
Rob Pike163ecda2009-12-16 12:31:18 +11002444 }
Rob Pikebb3e3092009-10-31 18:29:06 -07002445}
2446</pre>
2447<p>
2448There's clearly a lot more to do to make it realistic, but this
2449code is a framework for a rate-limited, parallel, non-blocking RPC
2450system, and there's not a mutex in sight.
2451</p>
2452
2453<h3 id="parallel">Parallelization</h3>
2454<p>
2455Another application of these ideas is to parallelize a calculation
2456across multiple CPU cores. If the calculation can be broken into
2457separate pieces, it can be parallelized, with a channel to signal
2458when each piece completes.
2459</p>
2460<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002461Let's say we have an expensive operation to perform on a vector of items,
Rob Pikebb3e3092009-10-31 18:29:06 -07002462and that the value of the operation on each item is independent,
2463as in this idealized example.
2464</p>
2465<pre>
Rob Pikec2b64182009-11-01 20:54:11 -08002466type Vector []float64
Rob Pikebb3e3092009-10-31 18:29:06 -07002467
Rob Pike617a6a52009-12-23 13:47:58 +11002468// Apply the operation to v[i], v[i+1] ... up to v[n-1].
Rob Pikec2b64182009-11-01 20:54:11 -08002469func (v Vector) DoSome(i, n int, u Vector, c chan int) {
Rob Pike77f6f162009-12-25 07:13:14 +11002470 for ; i &lt; n; i++ {
Rob Pikebb3e3092009-10-31 18:29:06 -07002471 v[i] += u.Op(v[i])
2472 }
Rob Pike77f6f162009-12-25 07:13:14 +11002473 c &lt;- 1 // signal that this piece is done
Rob Pikebb3e3092009-10-31 18:29:06 -07002474}
2475</pre>
2476<p>
2477We launch the pieces independently in a loop, one per CPU.
2478They can complete in any order but it doesn't matter; we just
2479count the completion signals by draining the channel after
2480launching all the goroutines.
2481</p>
2482<pre>
Rob Pike163ecda2009-12-16 12:31:18 +11002483const NCPU = 4 // number of CPU cores
Rob Pikebb3e3092009-10-31 18:29:06 -07002484
Rob Pikec2b64182009-11-01 20:54:11 -08002485func (v Vector) DoAll(u Vector) {
Rob Pike163ecda2009-12-16 12:31:18 +11002486 c := make(chan int, NCPU) // Buffering optional but sensible.
Rob Pike77f6f162009-12-25 07:13:14 +11002487 for i := 0; i &lt; NCPU; i++ {
Rob Pike163ecda2009-12-16 12:31:18 +11002488 go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c)
Rob Pikebb3e3092009-10-31 18:29:06 -07002489 }
2490 // Drain the channel.
Rob Pike77f6f162009-12-25 07:13:14 +11002491 for i := 0; i &lt; NCPU; i++ {
2492 &lt;-c // wait for one task to complete
Rob Pikebb3e3092009-10-31 18:29:06 -07002493 }
2494 // All done.
2495}
2496
2497</pre>
2498
Rob Pikedc3b4932009-11-15 13:09:43 -08002499<p>
2500The current implementation of <code>gc</code> (<code>6g</code>, etc.)
2501will not parallelize this code by default.
2502It dedicates only a single core to user-level processing. An
2503arbitrary number of goroutines can be blocked in system calls, but
2504by default only one can be executing user-level code at any time.
2505It should be smarter and one day it will be smarter, but until it
2506is if you want CPU parallelism you must tell the run-time
2507how many goroutines you want executing code simultaneously. There
2508are two related ways to do this. Either run your job with environment
2509variable <code>GOMAXPROCS</code> set to the number of cores to use
2510(default 1); or import the <code>runtime</code> package and call
2511<code>runtime.GOMAXPROCS(NCPU)</code>.
2512Again, this requirement is expected to be retired as the scheduling and run-time improve.
2513</p>
2514
Rob Pike430d4622009-10-20 12:30:39 -07002515<h3 id="leaky_buffer">A leaky buffer</h3>
2516
2517<p>
Rob Pikec2b64182009-11-01 20:54:11 -08002518The tools of concurrent programming can even make non-concurrent
Rob Pike430d4622009-10-20 12:30:39 -07002519ideas easier to express. Here's an example abstracted from an RPC
2520package. The client goroutine loops receiving data from some source,
2521perhaps a network. To avoid allocating and freeing buffers, it keeps
2522a free list, and uses a buffered channel to represent it. If the
2523channel is empty, a new buffer gets allocated.
2524Once the message buffer is ready, it's sent to the server on
2525<code>serverChan</code>.
2526</p>
2527<pre>
Russ Cox24ce19c2009-11-08 01:07:53 -08002528var freeList = make(chan *Buffer, 100)
2529var serverChan = make(chan *Buffer)
Rob Pike430d4622009-10-20 12:30:39 -07002530
2531func client() {
Rob Pike163ecda2009-12-16 12:31:18 +11002532 for {
Rob Pike61978aa2011-01-31 12:46:38 -08002533 var b *Buffer
2534 // Grab a buffer if available; allocate if not.
2535 select {
2536 case b = &lt;-freeList:
2537 // Got one; nothing more to do.
2538 default:
2539 // None free, so allocate a new one.
Rob Pike163ecda2009-12-16 12:31:18 +11002540 b = new(Buffer)
2541 }
Rob Pike61978aa2011-01-31 12:46:38 -08002542 load(b) // Read next message from the net.
2543 serverChan &lt;- b // Send to server.
Rob Pike163ecda2009-12-16 12:31:18 +11002544 }
Rob Pike430d4622009-10-20 12:30:39 -07002545}
2546</pre>
2547<p>
Rob Pike61978aa2011-01-31 12:46:38 -08002548The server loop receives each message from the client, processes it,
Rob Pike430d4622009-10-20 12:30:39 -07002549and returns the buffer to the free list.
2550</p>
2551<pre>
2552func server() {
Rob Pike163ecda2009-12-16 12:31:18 +11002553 for {
Rob Pike61978aa2011-01-31 12:46:38 -08002554 b := &lt;-serverChan // Wait for work.
Rob Pike163ecda2009-12-16 12:31:18 +11002555 process(b)
Rob Pike61978aa2011-01-31 12:46:38 -08002556 // Reuse buffer if there's room.
2557 select {
2558 case freeList &lt;- b:
2559 // Buffer on free list; nothing more to do.
2560 default:
2561 // Free list full, just carry on.
2562 }
Rob Pike163ecda2009-12-16 12:31:18 +11002563 }
Rob Pike430d4622009-10-20 12:30:39 -07002564}
2565</pre>
2566<p>
Rob Pike61978aa2011-01-31 12:46:38 -08002567The client attempts to retrieve a buffer from <code>freeList</code>;
2568if none is available, it allocates a fresh one.
2569The server's send to <code>freeList</code> puts <code>b</code> back
Rob Pike430d4622009-10-20 12:30:39 -07002570on the free list unless the list is full, in which case the
2571buffer is dropped on the floor to be reclaimed by
2572the garbage collector.
Rob Pike61978aa2011-01-31 12:46:38 -08002573(The <code>default</code> clauses in the <code>select</code>
2574statements execute when no other case is ready,
2575meaning that the <code>selects</code> never block.)
Rob Pike430d4622009-10-20 12:30:39 -07002576This implementation builds a leaky bucket free list
2577in just a few lines, relying on the buffered channel and
2578the garbage collector for bookkeeping.
2579</p>
2580
Rob Piked2228692009-10-12 21:18:23 -07002581<h2 id="errors">Errors</h2>
2582
2583<p>
2584Library routines must often return some sort of error indication to
2585the caller. As mentioned earlier, Go's multivalue return makes it
2586easy to return a detailed error description alongside the normal
2587return value. By convention, errors have type <code>os.Error</code>,
2588a simple interface.
2589</p>
2590<pre>
2591type Error interface {
Rob Pike163ecda2009-12-16 12:31:18 +11002592 String() string
Rob Piked2228692009-10-12 21:18:23 -07002593}
2594</pre>
2595<p>
2596A library writer is free to implement this interface with a
2597richer model under the covers, making it possible not only
2598to see the error but also to provide some context.
2599For example, <code>os.Open</code> returns an <code>os.PathError</code>.
2600</p>
2601<pre>
2602// PathError records an error and the operation and
2603// file path that caused it.
2604type PathError struct {
Rob Pike163ecda2009-12-16 12:31:18 +11002605 Op string // "open", "unlink", etc.
2606 Path string // The associated file.
2607 Error Error // Returned by the system call.
Rob Piked2228692009-10-12 21:18:23 -07002608}
2609
2610func (e *PathError) String() string {
Rob Pike163ecda2009-12-16 12:31:18 +11002611 return e.Op + " " + e.Path + ": " + e.Error.String()
Rob Piked2228692009-10-12 21:18:23 -07002612}
2613</pre>
2614<p>
2615<code>PathError</code>'s <code>String</code> generates
2616a string like this:
2617</p>
2618<pre>
2619open /etc/passwx: no such file or directory
2620</pre>
2621<p>
2622Such an error, which includes the problematic file name, the
2623operation, and the operating system error it triggered, is useful even
2624if printed far from the call that caused it;
2625it is much more informative than the plain
2626"no such file or directory".
2627</p>
2628
2629<p>
2630Callers that care about the precise error details can
2631use a type switch or a type assertion to look for specific
2632errors and extract details. For <code>PathErrors</code>
2633this might include examining the internal <code>Error</code>
2634field for recoverable failures.
2635</p>
2636
2637<pre>
Rob Pike77f6f162009-12-25 07:13:14 +11002638for try := 0; try &lt; 2; try++ {
Rob Pike163ecda2009-12-16 12:31:18 +11002639 file, err = os.Open(filename, os.O_RDONLY, 0)
2640 if err == nil {
2641 return
2642 }
2643 if e, ok := err.(*os.PathError); ok &amp;&amp; e.Error == os.ENOSPC {
2644 deleteTempFiles() // Recover some space.
2645 continue
2646 }
2647 return
Rob Piked2228692009-10-12 21:18:23 -07002648}
2649</pre>
2650
Rob Pike99b23a12010-06-18 10:52:37 -07002651<h3 id="panic">Panic</h3>
Rob Pike050905b2010-06-16 13:47:36 -07002652
2653<p>
Rob Pike99b23a12010-06-18 10:52:37 -07002654The usual way to report an error to a caller is to return an
2655<code>os.Error</code> as an extra return value. The canonical
2656<code>Read</code> method is a well-known instance; it returns a byte
2657count and an <code>os.Error</code>. But what if the error is
2658unrecoverable? Sometimes the program simply cannot continue.
2659</p>
2660
2661<p>
2662For this purpose, there is a built-in function <code>panic</code>
2663that in effect creates a run-time error that will stop the program
2664(but see the next section). The function takes a single argument
2665of arbitrary type&mdash;often a string&mdash;to be printed as the
2666program dies. It's also a way to indicate that something impossible has
2667happened, such as exiting an infinite loop. In fact, the compiler
2668recognizes a <code>panic</code> at the end of a function and
2669suppresses the usual check for a <code>return</code> statement.
2670</p>
2671
2672
2673<pre>
2674// A toy implementation of cube root using Newton's method.
2675func CubeRoot(x float64) float64 {
2676 z := x/3 // Arbitrary intitial value
Robert Griesemer76f32282011-02-04 08:43:21 -08002677 for i := 0; i &lt; 1e6; i++ {
Rob Pike99b23a12010-06-18 10:52:37 -07002678 prevz := z
2679 z -= (z*z*z-x) / (3*z*z)
2680 if veryClose(z, prevz) {
2681 return z
2682 }
2683 }
2684 // A million iterations has not converged; something is wrong.
Christopher Wedgwoodc80746a2010-08-19 10:03:58 +10002685 panic(fmt.Sprintf("CubeRoot(%g) did not converge", x))
Rob Pike99b23a12010-06-18 10:52:37 -07002686}
2687</pre>
2688
2689<p>
2690This is only an example but real library functions should
2691avoid <code>panic</code>. If the problem can be masked or worked
2692around, it's always better to let things continue to run rather
2693than taking down the whole program. One possible counterexample
2694is during initialization: if the library truly cannot set itself up,
2695it might be reasonable to panic, so to speak.
2696</p>
2697
2698<pre>
2699var user = os.Getenv("USER")
2700
2701func init() {
2702 if user == "" {
2703 panic("no value for $USER")
2704 }
2705}
2706</pre>
2707
2708<h3 id="recover">Recover</h3>
2709
2710<p>
2711When <code>panic</code> is called, including implicitly for run-time
Robert Griesemerbd4e49f2011-02-02 11:02:56 -08002712errors such as indexing an array out of bounds or failing a type
Rob Pike99b23a12010-06-18 10:52:37 -07002713assertion, it immediately stops execution of the current function
2714and begins unwinding the stack of the goroutine, running any deferred
2715functions along the way. If that unwinding reaches the top of the
2716goroutine's stack, the program dies. However, it is possible to
2717use the built-in function <code>recover</code> to regain control
2718of the goroutine and resume normal execution.
2719</p>
2720
2721<p>
2722A call to <code>recover</code> stops the unwinding and returns the
2723argument passed to <code>panic</code>. Because the only code that
2724runs while unwinding is inside deferred functions, <code>recover</code>
2725is only useful inside deferred functions.
2726</p>
2727
2728<p>
2729One application of <code>recover</code> is to shut down a failing goroutine
2730inside a server without killing the other executing goroutines.
2731</p>
2732
2733<pre>
Robert Griesemer76f32282011-02-04 08:43:21 -08002734func server(workChan &lt;-chan *Work) {
Rob Pike99b23a12010-06-18 10:52:37 -07002735 for work := range workChan {
Rob Pike7ddbe792010-08-24 12:37:51 +10002736 go safelyDo(work)
Rob Pike99b23a12010-06-18 10:52:37 -07002737 }
2738}
2739
2740func safelyDo(work *Work) {
2741 defer func() {
2742 if err := recover(); err != nil {
Rob Pikee787f8272010-10-12 16:56:50 -07002743 log.Println("work failed:", err)
Rob Pike99b23a12010-06-18 10:52:37 -07002744 }
2745 }()
2746 do(work)
2747}
2748</pre>
2749
2750<p>
2751In this example, if <code>do(work)</code> panics, the result will be
2752logged and the goroutine will exit cleanly without disturbing the
2753others. There's no need to do anything else in the deferred closure;
2754calling <code>recover</code> handles the condition completely.
2755</p>
2756
2757<p>
Robert Griesemer76f32282011-02-04 08:43:21 -08002758Because <code>recover</code> always returns <code>nil</code> unless called directly
2759from a deferred function, deferred code can call library routines that themselves
2760use <code>panic</code> and <code>recover</code> without failing. As an example,
2761the deferred function in <code>safelyDo</code> might call a logging function before
2762calling <code>recover</code>, and that logging code would run unaffected
2763by the panicking state.
2764</p>
2765
2766<p>
2767With our recovery pattern in place, the <code>do</code>
Rob Pike99b23a12010-06-18 10:52:37 -07002768function (and anything it calls) can get out of any bad situation
2769cleanly by calling <code>panic</code>. We can use that idea to
2770simplify error handling in complex software. Let's look at an
2771idealized excerpt from the <code>regexp</code> package, which reports
2772parsing errors by calling <code>panic</code> with a local
2773<code>Error</code> type. Here's the definition of <code>Error</code>,
2774an <code>error</code> method, and the <code>Compile</code> function.
2775</p>
2776
2777<pre>
2778// Error is the type of a parse error; it satisfies os.Error.
2779type Error string
2780func (e Error) String() string {
2781 return string(e)
2782}
2783
2784// error is a method of *Regexp that reports parsing errors by
2785// panicking with an Error.
2786func (regexp *Regexp) error(err string) {
2787 panic(Error(err))
2788}
2789
2790// Compile returns a parsed representation of the regular expression.
2791func Compile(str string) (regexp *Regexp, err os.Error) {
2792 regexp = new(Regexp)
2793 // doParse will panic if there is a parse error.
2794 defer func() {
2795 if e := recover(); e != nil {
2796 regexp = nil // Clear return value.
2797 err = e.(Error) // Will re-panic if not a parse error.
2798 }
2799 }()
2800 return regexp.doParse(str), nil
2801}
2802</pre>
2803
2804<p>
2805If <code>doParse</code> panics, the recovery block will set the
2806return value to <code>nil</code>&mdash;deferred functions can modify
2807named return values. It then will then check, in the assignment
2808to <code>err</code>, that the problem was a parse error by asserting
2809that it has type <code>Error</code>.
2810If it does not, the type assertion will fail, causing a run-time error
2811that continues the stack unwinding as though nothing had interrupted
2812it. This check means that if something unexpected happens, such
2813as an array index out of bounds, the code will fail even though we
2814are using <code>panic</code> and <code>recover</code> to handle
2815user-triggered errors.
2816</p>
2817
2818<p>
Rob Pike29d0f022011-01-05 11:39:57 -08002819With error handling in place, the <code>error</code> method
Rob Pike99b23a12010-06-18 10:52:37 -07002820makes it easy to report parse errors without worrying about unwinding
2821the parse stack by hand.
2822</p>
2823
2824<p>
2825Useful though this pattern is, it should be used only within a package.
2826<code>Parse</code> turns its internal <code>panic</code> calls into
2827<code>os.Error</code> values; it does not expose <code>panics</code>
2828to its client. That is a good rule to follow.
Rob Pike050905b2010-06-16 13:47:36 -07002829</p>
2830
Rob Pike29d0f022011-01-05 11:39:57 -08002831<p>
2832By the way, this re-panic idiom changes the panic value if an actual
2833error occurs. However, both the original and new failures will be
2834presented in the crash report, so the root cause of the problem will
2835still be visible. Thus this simple re-panic approach is usually
2836sufficient&mdash;it's a crash after all&mdash;but if you want to
2837display only the original value, you can write a little more code to
2838filter unexpected problems and re-panic with the original error.
2839That's left as an exercise for the reader.
2840</p>
2841
Rob Pike050905b2010-06-16 13:47:36 -07002842
Rob Pike31053d42009-11-04 17:29:20 -08002843<h2 id="web_server">A web server</h2>
2844
2845<p>
2846Let's finish with a complete Go program, a web server.
2847This one is actually a kind of web re-server.
2848Google provides a service at
2849<a href="http://chart.apis.google.com">http://chart.apis.google.com</a>
2850that does automatic formatting of data into charts and graphs.
2851It's hard to use interactively, though,
2852because you need to put the data into the URL as a query.
2853The program here provides a nicer interface to one form of data: given a short piece of text,
2854it calls on the chart server to produce a QR code, a matrix of boxes that encode the
2855text.
2856That image can be grabbed with your cell phone's camera and interpreted as,
2857for instance, a URL, saving you typing the URL into the phone's tiny keyboard.
2858</p>
2859<p>
2860Here's the complete program.
2861An explanation follows.
2862</p>
2863
2864<pre>
2865package main
2866
2867import (
Rob Pike163ecda2009-12-16 12:31:18 +11002868 "flag"
2869 "http"
2870 "io"
2871 "log"
Rob Pike163ecda2009-12-16 12:31:18 +11002872 "template"
Rob Pike31053d42009-11-04 17:29:20 -08002873)
2874
Russ Cox24ce19c2009-11-08 01:07:53 -08002875var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18
Rob Pike31053d42009-11-04 17:29:20 -08002876var fmap = template.FormatterMap{
Rob Pike163ecda2009-12-16 12:31:18 +11002877 "html": template.HTMLFormatter,
2878 "url+html": UrlHtmlFormatter,
Rob Pike31053d42009-11-04 17:29:20 -08002879}
2880var templ = template.MustParse(templateStr, fmap)
2881
2882func main() {
Rob Pike163ecda2009-12-16 12:31:18 +11002883 flag.Parse()
2884 http.Handle("/", http.HandlerFunc(QR))
2885 err := http.ListenAndServe(*addr, nil)
2886 if err != nil {
Rob Pikeeea18d92011-02-01 12:47:35 -08002887 log.Fatal("ListenAndServe:", err)
Rob Pike163ecda2009-12-16 12:31:18 +11002888 }
Rob Pike31053d42009-11-04 17:29:20 -08002889}
2890
Rob Pike1edfb4c2010-09-29 11:12:52 -07002891func QR(w http.ResponseWriter, req *http.Request) {
Rob Pikefb9e37c2011-02-09 14:23:01 -08002892 templ.Execute(w, req.FormValue("s"))
Rob Pike31053d42009-11-04 17:29:20 -08002893}
2894
Nigel Taobf453eb2011-01-04 15:52:03 +11002895func UrlHtmlFormatter(w io.Writer, fmt string, v ...interface{}) {
2896 template.HTMLEscape(w, []byte(http.URLEscape(v[0].(string))))
Rob Pike31053d42009-11-04 17:29:20 -08002897}
2898
2899
2900const templateStr = `
2901&lt;html&gt;
2902&lt;head&gt;
2903&lt;title&gt;QR Link Generator&lt;/title&gt;
2904&lt;/head&gt;
2905&lt;body&gt;
2906{.section @}
2907&lt;img src="http://chart.apis.google.com/chart?chs=300x300&amp;cht=qr&amp;choe=UTF-8&amp;chl={@|url+html}"
2908/&gt;
2909&lt;br&gt;
2910{@|html}
2911&lt;br&gt;
2912&lt;br&gt;
2913{.end}
2914&lt;form action="/" name=f method="GET"&gt;&lt;input maxLength=1024 size=70
2915name=s value="" title="Text to QR Encode"&gt;&lt;input type=submit
2916value="Show QR" name=qr&gt;
2917&lt;/form&gt;
2918&lt;/body&gt;
2919&lt;/html&gt;
2920`
2921</pre>
2922
2923<p>
2924The pieces up to <code>main</code> should be easy to follow.
2925The one flag sets a default HTTP port for our server. The template
2926variable <code>templ</code> is where the fun happens. It builds an HTML template
2927that will be executed by the server to display the page; more about
2928that in a moment.
2929</p>
2930<p>
2931The <code>main</code> function parses the flags and, using the mechanism
2932we talked about above, binds the function <code>QR</code> to the root path
2933for the server. Then <code>http.ListenAndServe</code> is called to start the
2934server; it blocks while the server runs.
2935</p>
2936<p>
2937<code>QR</code> just receives the request, which contains form data, and
Russ Cox24ce19c2009-11-08 01:07:53 -08002938executes the template on the data in the form value named <code>s</code>.
Rob Pike31053d42009-11-04 17:29:20 -08002939</p>
2940<p>
2941The template package, inspired by <a
2942href="http://code.google.com/p/json-template">json-template</a>, is
2943powerful;
2944this program just touches on its capabilities.
2945In essence, it rewrites a piece of text on the fly by substituting elements derived
2946from data items passed to <code>templ.Execute</code>, in this case the
Russ Cox24ce19c2009-11-08 01:07:53 -08002947form value.
Rob Pike31053d42009-11-04 17:29:20 -08002948Within the template text (<code>templateStr</code>),
2949brace-delimited pieces denote template actions.
2950The piece from the <code>{.section @}</code>
2951to <code>{.end}</code> executes with the value of the data item <code>@</code>,
Russ Cox24ce19c2009-11-08 01:07:53 -08002952which is a shorthand for &ldquo;the current item&rdquo;, which is the form value.
Rob Pike31053d42009-11-04 17:29:20 -08002953(When the string is empty, this piece of the template is suppressed.)
2954</p>
2955<p>
2956The snippet <code>{@|url+html}</code> says to run the data through the formatter
2957installed in the formatter map (<code>fmap</code>)
2958under the name <code>"url+html"</code>.
2959That is the function <code>UrlHtmlFormatter</code>, which sanitizes the string
2960for safe display on the web page.
2961</p>
2962<p>
2963The rest of the template string is just the HTML to show when the page loads.
2964If this is too quick an explanation, see the <a href="/pkg/template/">documentation</a>
2965for the template package for a more thorough discussion.
2966</p>
2967<p>
2968And there you have it: a useful webserver in a few lines of code plus some
2969data-driven HTML text.
2970Go is powerful enough to make a lot happen in a few lines.
2971</p>
2972
Rob Pike6f89f3f2009-10-20 17:32:16 -07002973<!--
Rob Pike3e740792009-10-05 14:48:57 -07002974TODO
Rob Pike163ecda2009-12-16 12:31:18 +11002975<pre>
2976verifying implementation
2977type Color uint32
2978
2979// Check that Color implements image.Color and image.Image
2980var _ image.Color = Black
2981var _ image.Image = Black
2982</pre>
Rob Pike8aec6122009-09-02 16:41:41 -07002983-->
Rob Pike6f89f3f2009-10-20 17:32:16 -07002984