blob: aeed53795674a5fbae87981ced78e06c27be849d [file] [log] [blame]
Rob Pike6898f952009-11-09 23:54:35 -08001<!-- FAQ -->
Russ Cox32274452009-10-22 00:13:51 -07002
3<h2 id="Origins">Origins</h2>
4
5<h3 id="What_is_the_purpose_of_the_project">
6What is the purpose of the project?</h3>
7
8<p>
9No major systems language has emerged in over a decade, but over that time
10the computing landscape has changed tremendously. There are several trends:
Rob Pike93c4a242011-08-06 07:41:55 +100011</p>
Russ Cox32274452009-10-22 00:13:51 -070012
13<ul>
14<li>
15Computers are enormously quicker but software development is not faster.
16<li>
17Dependency management is a big part of software development today but the
Russ Coxe434f1a2009-11-07 17:31:22 -080018&ldquo;header files&rdquo; of languages in the C tradition are antithetical to clean
Russ Cox32274452009-10-22 00:13:51 -070019dependency analysis&mdash;and fast compilation.
20<li>
21There is a growing rebellion against cumbersome type systems like those of
22Java and C++, pushing people towards dynamically typed languages such as
Rob Pike0c2a4792009-11-01 20:50:42 -080023Python and JavaScript.
Russ Cox32274452009-10-22 00:13:51 -070024<li>
25Some fundamental concepts such as garbage collection and parallel computation
26are not well supported by popular systems languages.
27<li>
28The emergence of multicore computers has generated worry and confusion.
29</ul>
30
31<p>
32We believe it's worth trying again with a new language, a concurrent,
33garbage-collected language with fast compilation. Regarding the points above:
Rob Pike93c4a242011-08-06 07:41:55 +100034</p>
Russ Cox32274452009-10-22 00:13:51 -070035
36<ul>
37<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080038It is possible to compile a large Go program in a few seconds on a single computer.
Russ Cox32274452009-10-22 00:13:51 -070039<li>
40Go provides a model for software construction that makes dependency
41analysis easy and avoids much of the overhead of C-style include files and
42libraries.
43<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080044Go's type system has no hierarchy, so no time is spent defining the
45relationships between types. Also, although Go has static types the language
Russ Cox32274452009-10-22 00:13:51 -070046attempts to make types feel lighter weight than in typical OO languages.
47<li>
48Go is fully garbage-collected and provides fundamental support for
49concurrent execution and communication.
50<li>
51By its design, Go proposes an approach for the construction of system
52software on multicore machines.
53</ul>
54
55<h3 id="What_is_the_origin_of_the_name">
56What is the origin of the name?</h3>
57
58<p>
Russ Coxe434f1a2009-11-07 17:31:22 -080059&ldquo;Ogle&rdquo; would be a good name for a Go debugger.
Evan Shaw64d85762011-05-22 14:56:12 +100060</p>
Russ Cox32274452009-10-22 00:13:51 -070061
Rob Pikebdecae92009-11-23 17:34:23 -080062<h3 id="Whats_the_origin_of_the_mascot">
63What's the origin of the mascot?</h3>
64
65<p>
66The mascot and logo were designed by
67<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
68<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
69the Plan 9 bunny.
70The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
71T-shirt design some years ago.
72The logo and mascot are covered by the
73<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
74license.
75</p>
76
Andrew Gerrand4164d602010-09-29 16:52:22 +100077<h3 id="What_kind_of_a_name_is_6g">
78What kind of a name is 6g?</h3>
79
80<p>
81The <code>6g</code> (and <code>8g</code> and <code>5g</code>) compiler is named in the
82tradition of the Plan 9 C compilers, described in
83<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">
84http://plan9.bell-labs.com/sys/doc/compiler.html</a>
85(see the table in section 2).
86
87<code>6</code> is the architecture letter for amd64 (or x86-64, if you prefer), while
88<code>g</code> stands for Go.
Evan Shaw64d85762011-05-22 14:56:12 +100089</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +100090
91<h3 id="history">
92What is the history of the project?</h3>
93<p>
94Robert Griesemer, Rob Pike and Ken Thompson started sketching the
95goals for a new language on the white board on September 21, 2007.
96Within a few days the goals had settled into a plan to do something
97and a fair idea of what it would be. Design continued part-time in
98parallel with unrelated work. By January 2008, Ken had started work
99on a compiler with which to explore ideas; it generated C code as its
100output. By mid-year the language had become a full-time project and
101had settled enough to attempt a production compiler. In May 2008,
102Ian Taylor independently started on a GCC front end for Go using the
103draft specification. Russ Cox joined in late 2008 and helped move the language
104and libraries from prototype to reality.
105</p>
106
107<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000108Go became a public open source project on November 10, 2009.
109Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000110</p>
111
Andrew Gerrand4164d602010-09-29 16:52:22 +1000112<h3 id="creating_a_new_language">
113Why are you creating a new language?</h3>
114<p>
115Go was born out of frustration with existing languages and
116environments for systems programming. Programming had become too
117difficult and the choice of languages was partly to blame. One had to
118choose either efficient compilation, efficient execution, or ease of
119programming; all three were not available in the same mainstream
120language. Programmers who could were choosing ease over
121safety and efficiency by moving to dynamically typed languages such as
122Python and JavaScript rather than C++ or, to a lesser extent, Java.
123</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000124
Andrew Gerrand4164d602010-09-29 16:52:22 +1000125<p>
126Go is an attempt to combine the ease of programming of an interpreted,
127dynamically typed
128language with the efficiency and safety of a statically typed, compiled language.
129It also aims to be modern, with support for networked and multicore
130computing. Finally, it is intended to be <i>fast</i>: it should take
131at most a few seconds to build a large executable on a single computer.
132To meet these goals required addressing a number of
133linguistic issues: an expressive but lightweight type system;
134concurrency and garbage collection; rigid dependency specification;
135and so on. These cannot be addressed well by libraries or tools; a new
136language was called for.
137</p>
138
Andrew Gerrand4164d602010-09-29 16:52:22 +1000139<h3 id="ancestors">
140What are Go's ancestors?</h3>
141<p>
142Go is mostly in the C family (basic syntax),
143with significant input from the Pascal/Modula/Oberon
144family (declarations, packages),
145plus some ideas from languages
146inspired by Tony Hoare's CSP,
147such as Newsqueak and Limbo (concurrency).
148However, it is a new language across the board.
149In every respect the language was designed by thinking
150about what programmers do and how to make programming, at least the
151kind of programming we do, more effective, which means more fun.
152</p>
153
Andrew Gerrand4164d602010-09-29 16:52:22 +1000154<h3 id="principles">
155What are the guiding principles in the design?</h3>
156<p>
157Programming today involves too much bookkeeping, repetition, and
158clerical work. As Dick Gabriel says, &ldquo;Old programs read
159like quiet conversations between a well-spoken research worker and a
160well-studied mechanical colleague, not as a debate with a compiler.
161Who'd have guessed sophistication bought such noise?&rdquo;
162The sophistication is worthwhile&mdash;no one wants to go back to
163the old languages&mdash;but can it be more quietly achieved?
164</p>
165<p>
166Go attempts to reduce the amount of typing in both senses of the word.
167Throughout its design, we have tried to reduce clutter and
168complexity. There are no forward declarations and no header files;
169everything is declared exactly once. Initialization is expressive,
170automatic, and easy to use. Syntax is clean and light on keywords.
171Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
172simple type derivation using the <code>:=</code>
173declare-and-initialize construct. And perhaps most radically, there
174is no type hierarchy: types just <i>are</i>, they don't have to
175announce their relationships. These simplifications allow Go to be
176expressive yet comprehensible without sacrificing, well, sophistication.
177</p>
178<p>
179Another important principle is to keep the concepts orthogonal.
180Methods can be implemented for any type; structures represent data while
181interfaces represent abstraction; and so on. Orthogonality makes it
182easier to understand what happens when things combine.
183</p>
184
Russ Cox32274452009-10-22 00:13:51 -0700185<h2 id="Usage">Usage</h2>
186
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000187<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800188
Evan Shaw64d85762011-05-22 14:56:12 +1000189<p>
190Yes. There are now several Go programs deployed in
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000191production inside Google. For instance, the server behind
192<a href="http://golang.org">http://golang.org</a> is a Go program;
193in fact it's just the <a href="/cmd/godoc"><code>godoc</code></a>
194document server running in a production configuration.
Evan Shaw64d85762011-05-22 14:56:12 +1000195</p>
Rob Pike7685a672009-11-09 20:25:45 -0800196
Russ Cox32274452009-10-22 00:13:51 -0700197<h3 id="Do_Go_programs_link_with_Cpp_programs">
198Do Go programs link with C/C++ programs?</h3>
199
200<p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000201There are two Go compiler implementations, <code>6g</code> and friends,
202generically called <code>gc</code>, and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800203<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700204therefore only be linked with C programs using the same convention.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000205There is such a C compiler but no C++ compiler.
206<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
207GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000208</p>
Russ Cox32274452009-10-22 00:13:51 -0700209
210<p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000211The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
212&ldquo;foreign function interface&rdquo; to allow safe calling of
213C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000214</p>
215
Russ Cox32274452009-10-22 00:13:51 -0700216
Rob Pike0c2a4792009-11-01 20:50:42 -0800217<h3 id="Does_Go_support_Google_protocol_buffers">
218Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700219
220<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700221A separate open source project provides the necessary compiler plugin and library.
222It is available at
223<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
224</p>
Russ Cox32274452009-10-22 00:13:51 -0700225
Evan Shaw64d85762011-05-22 14:56:12 +1000226
Russ Cox6301fb42009-12-03 17:23:33 -0800227<h3 id="Can_I_translate_the_Go_home_page">
228Can I translate the Go home page into another language?</h3>
229
230<p>
231Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000232However, if you choose to add the Google logo or branding to your site
Russ Cox6301fb42009-12-03 17:23:33 -0800233(it does not appear on <a href="http://golang.org/">golang.org</a>),
234you will need to abide by the guidelines at
235<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
236</p>
237
Russ Cox32274452009-10-22 00:13:51 -0700238<h2 id="Design">Design</h2>
239
Andrew Gerrand4164d602010-09-29 16:52:22 +1000240<h3 id="unicode_identifiers">
241What's up with Unicode identifiers?</h3>
242
243<p>
244It was important to us to extend the space of identifiers from the
245confines of ASCII. Go's rule&mdash;identifier characters must be
246letters or digits as defined by Unicode&mdash;is simple to understand
247and to implement but has restrictions. Combining characters are
248excluded by design, for instance.
249Until there
250is an agreed external definition of what an identifier might be,
251plus a definition of canonicalization of identifiers that guarantees
252no ambiguity, it seemed better to keep combining characters out of
253the mix. Thus we have a simple rule that can be expanded later
254without breaking programs, one that avoids bugs that would surely arise
255from a rule that admits ambiguous identifiers.
256</p>
257
258<p>
259On a related note, since an exported identifier must begin with an
260upper-case letter, identifiers created from &ldquo;letters&rdquo;
261in some languages can, by definition, not be exported. For now the
262only solution is to use something like <code>X日本語</code>, which
263is clearly unsatisfactory; we are considering other options. The
264case-for-visibility rule is unlikely to change however; it's one
265of our favorite features of Go.
266</p>
267
268<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700269
270<p>
271Every language contains novel features and omits someone's favorite
272feature. Go was designed with an eye on felicity of programming, speed of
273compilation, orthogonality of concepts, and the need to support features
274such as concurrency and garbage collection. Your favorite feature may be
275missing because it doesn't fit, because it affects compilation speed or
276clarity of design, or because it would make the fundamental system model
277too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000278</p>
Russ Cox32274452009-10-22 00:13:51 -0700279
280<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800281If it bothers you that Go is missing feature <var>X</var>,
282please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700283they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000284</p>
Russ Cox32274452009-10-22 00:13:51 -0700285
Andrew Gerrand4164d602010-09-29 16:52:22 +1000286<h3 id="generics">
287Why does Go not have generic types?</h3>
288<p>
289Generics may well be added at some point. We don't feel an urgency for
290them, although we understand some programmers do.
291</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000292
Andrew Gerrand4164d602010-09-29 16:52:22 +1000293<p>
294Generics are convenient but they come at a cost in
295complexity in the type system and run-time. We haven't yet found a
296design that gives value proportionate to the complexity, although we
297continue to think about it. Meanwhile, Go's built-in maps and slices,
298plus the ability to use the empty interface to construct containers
299(with explicit unboxing) mean in many cases it is possible to write
300code that does what generics would enable, if less smoothly.
301</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000302
Andrew Gerrand4164d602010-09-29 16:52:22 +1000303<p>
304This remains an open issue.
305</p>
306
307<h3 id="exceptions">
308Why does Go not have exceptions?</h3>
309<p>
310We believe that coupling exceptions to a control
311structure, as in the <code>try-catch-finally</code> idiom, results in
312convoluted code. It also tends to encourage programmers to label
313too many ordinary errors, such as failing to open a file, as
314exceptional.
315</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000316
Andrew Gerrand4164d602010-09-29 16:52:22 +1000317<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000318Go takes a different approach. For plain error handling, Go's multi-value
319returns make it easy to report an error without overloading the return value.
320<a href="http://blog.golang.org/2011/07/error-handling-and-go.html">A
321canonical error type, coupled
322with Go's other features</a>, makes error
323handling pleasant but quite different from that in other languages.
324</p>
325
326<p>
327Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000328of built-in functions to signal and recover from truly exceptional
329conditions. The recovery mechanism is executed only as part of a
330function's state being torn down after an error, which is sufficient
331to handle catastrophe but requires no extra control structures and,
332when used well, can result in clean error-handling code.
333</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000334
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000335<p>
336See the <a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a> article for details.
337</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000338
Andrew Gerrand4164d602010-09-29 16:52:22 +1000339<h3 id="assertions">
340Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700341
342<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000343Go doesn't provide assertions. They are undeniably convenient, but our
344experience has been that programmers use them as a crutch to avoid thinking
345about proper error handling and reporting. Proper error handling means that
346servers continue operation after non-fatal errors instead of crashing.
347Proper error reporting means that errors are direct and to the point,
348saving the programmer from interpreting a large crash trace. Precise
349errors are particularly important when the programmer seeing the errors is
350not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000351</p>
Russ Cox32274452009-10-22 00:13:51 -0700352
Andrew Gerrand4164d602010-09-29 16:52:22 +1000353<p>
354The same arguments apply to the use of <code>assert()</code> in test programs. Proper
355error handling means letting other tests run after one has failed, so
356that the person debugging the failure gets a complete picture of what is
357wrong. It is more useful for a test to report that
358<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
3592, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
360answer for 2 and therefore no more tests were run. The programmer who
361triggers the test failure may not be familiar with the code that fails.
362Time invested writing a good error message now pays off later when the
363test breaks.
Evan Shaw64d85762011-05-22 14:56:12 +1000364</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000365
366<p>
367In testing, if the amount of extra code required to write
368good errors seems repetitive and overwhelming, it might work better as a
369table-driven test instead.
370Go has excellent support for data structure literals.
Evan Shaw64d85762011-05-22 14:56:12 +1000371</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000372
373<p>
374We understand that this is a point of contention. There are many things in
375the Go language and libraries that differ from modern practices, simply
376because we feel it's sometimes worth trying a different approach.
Evan Shaw64d85762011-05-22 14:56:12 +1000377</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000378
379<h3 id="csp">
380Why build concurrency on the ideas of CSP?</h3>
381<p>
382Concurrency and multi-threaded programming have a reputation
383for difficulty. We believe the problem is due partly to complex
384designs such as pthreads and partly to overemphasis on low-level details
Rob Pike93c4a242011-08-06 07:41:55 +1000385such as mutexes, condition variables, and memory barriers.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000386Higher-level interfaces enable much simpler code, even if there are still
387mutexes and such under the covers.
388</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000389
Andrew Gerrand4164d602010-09-29 16:52:22 +1000390<p>
391One of the most successful models for providing high-level linguistic support
392for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
393Occam and Erlang are two well known languages that stem from CSP.
394Go's concurrency primitives derive from a different part of the family tree
395whose main contribution is the powerful notion of channels as first class objects.
396</p>
397
398<h3 id="goroutines">
399Why goroutines instead of threads?</h3>
400<p>
401Goroutines are part of making concurrency easy to use. The idea, which has
402been around for a while, is to multiplex independently executing
Rob Pike93c4a242011-08-06 07:41:55 +1000403functions&mdash;coroutines&mdash;onto a set of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000404When a coroutine blocks, such as by calling a blocking system call,
405the run-time automatically moves other coroutines on the same operating
406system thread to a different, runnable thread so they won't be blocked.
407The programmer sees none of this, which is the point.
408The result, which we call goroutines, can be very cheap: unless they spend a lot of time
409in long-running system calls, they cost little more than the memory
Rob Pike93c4a242011-08-06 07:41:55 +1000410for the stack, which is just a few kilobytes.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000411</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000412
Andrew Gerrand4164d602010-09-29 16:52:22 +1000413<p>
414To make the stacks small, Go's run-time uses segmented stacks. A newly
415minted goroutine is given a few kilobytes, which is almost always enough.
416When it isn't, the run-time allocates (and frees) extension segments automatically.
417The overhead averages about three cheap instructions per function call.
418It is practical to create hundreds of thousands of goroutines in the same
419address space. If goroutines were just threads, system resources would
420run out at a much smaller number.
421</p>
422
423<h3 id="atomic_maps">
424Why are map operations not defined to be atomic?</h3>
425
426<p>
427After long discussion it was decided that the typical use of maps did not require
428safe access from multiple threads, and in those cases where it did, the map was
429probably part of some larger data structure or computation that was already
430synchronized. Therefore requiring that all map operations grab a mutex would slow
431down most programs and add safety to few. This was not an easy decision,
432however, since it means uncontrolled map access can crash the program.
433</p>
434
435<p>
436The language does not preclude atomic map updates. When required, such
437as when hosting an untrusted program, the implementation could interlock
438map access.
439</p>
440
Andrew Gerrand4164d602010-09-29 16:52:22 +1000441<h2 id="types">Types</h2>
Russ Cox32274452009-10-22 00:13:51 -0700442
443<h3 id="Is_Go_an_object-oriented_language">
444Is Go an object-oriented language?</h3>
445
446<p>
447Yes and no. Although Go has types and methods and allows an
448object-oriented style of programming, there is no type hierarchy.
Russ Coxe434f1a2009-11-07 17:31:22 -0800449The concept of &ldquo;interface&rdquo; in Go provides a different approach that
Russ Cox32274452009-10-22 00:13:51 -0700450we believe is easy to use and in some ways more general. There are
451also ways to embed types in other types to provide something
452analogous&mdash;but not identical&mdash;to subclassing.
Rob Pike0c2a4792009-11-01 20:50:42 -0800453Moreover, methods in Go are more general than in C++ or Java:
454they can be defined for any sort of data, not just structs.
Evan Shaw64d85762011-05-22 14:56:12 +1000455</p>
Russ Cox32274452009-10-22 00:13:51 -0700456
457<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800458Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800459lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000460</p>
Russ Cox32274452009-10-22 00:13:51 -0700461
462<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
463How do I get dynamic dispatch of methods?</h3>
464
465<p>
466The only way to have dynamically dispatched methods is through an
467interface. Methods on structs or other types are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000468</p>
Russ Cox32274452009-10-22 00:13:51 -0700469
Andrew Gerrand4164d602010-09-29 16:52:22 +1000470<h3 id="inheritance">
471Why is there no type inheritance?</h3>
472<p>
473Object-oriented programming, at least in the best-known languages,
474involves too much discussion of the relationships between types,
475relationships that often could be derived automatically. Go takes a
476different approach.
477</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000478
Andrew Gerrand4164d602010-09-29 16:52:22 +1000479<p>
480Rather than requiring the programmer to declare ahead of time that two
481types are related, in Go a type automatically satisfies any interface
482that specifies a subset of its methods. Besides reducing the
483bookkeeping, this approach has real advantages. Types can satisfy
484many interfaces at once, without the complexities of traditional
485multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000486Interfaces can be very lightweight&mdash;an interface with
487one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000488Interfaces can be added after the fact if a new idea comes along
489or for testing&mdash;without annotating the original types.
490Because there are no explicit relationships between types
491and interfaces, there is no type hierarchy to manage or discuss.
492</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000493
Andrew Gerrand4164d602010-09-29 16:52:22 +1000494<p>
495It's possible to use these ideas to construct something analogous to
496type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
497enables formatted printing to any output, not just a file, or how the
498<code>bufio</code> package can be completely separate from file I/O,
499or how the <code>crypto</code> packages stitch together block and
500stream ciphers. All these ideas stem from a single interface
501(<code>io.Writer</code>) representing a single method
502(<code>Write</code>). And that's only scratching the surface.
503</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000504
Andrew Gerrand4164d602010-09-29 16:52:22 +1000505<p>
506It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000507dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000508</p>
509
510<h3 id="methods_on_basics">
511Why is <code>len</code> a function and not a method?</h3>
512<p>
513We debated this issue but decided
514implementing <code>len</code> and friends as functions was fine in practice and
515didn't complicate questions about the interface (in the Go type sense)
516of basic types.
517</p>
518
519<h3 id="overloading">
520Why does Go not support overloading of methods and operators?</h3>
521<p>
522Method dispatch is simplified if it doesn't need to do type matching as well.
523Experience with other languages told us that having a variety of
524methods with the same name but different signatures was occasionally useful
525but that it could also be confusing and fragile in practice. Matching only by name
526and requiring consistency in the types was a major simplifying decision
527in Go's type system.
528</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000529
Andrew Gerrand4164d602010-09-29 16:52:22 +1000530<p>
531Regarding operator overloading, it seems more a convenience than an absolute
532requirement. Again, things are simpler without it.
533</p>
534
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100535<h3 id="implements_interface">
536Why doesn't Go have "implements" declarations?</h3>
537
538<p>
539A Go type satisfies an interface by implementing the methods of that interface,
540nothing more. This property allows interfaces to be defined and used without
541having to modify existing code. It enables a kind of "duck typing" that
542promotes separation of concerns and improves code re-use, and makes it easier
543to build on patterns that emerge as the code develops.
544The semantics of interfaces is one of the main reasons for Go's nimble,
545lightweight feel.
546</p>
547
548<p>
549See the <a href="#inheritance">question on type inheritance</a> for more detail.
550</p>
551
552<h3 id="guarantee_satisfies_interface">
553How can I guarantee my type satisfies an interface?</h3>
554
555<p>
556You can ask the compiler to check that the type <code>T</code> implements the
557interface <code>I</code> by attempting an assignment:
558</p>
559
560<pre>
561type T struct{}
562var _ I = T{}
563</pre>
564
565<p>
566If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
567at compile time.
568</p>
569
570<p>
571If you wish the users of an interface to explicitly declare that they implement
572it, you can add a method with a descriptive name to the interface's method set.
573For example:
574</p>
575
576<pre>
577type Fooer interface {
578 Foo()
579 ImplementsFooer()
580}
581</pre>
582
583<p>
584A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100585<code>Fooer</code>, clearly documenting the fact and announcing it in
586<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100587</p>
588
589<pre>
590type Bar struct{}
591func (b Bar) ImplementsFooer() {}
592func (b Bar) Foo() {}
593</pre>
594
595<p>
596Most code doesn't make use of such constraints, since they limit the utility of
597the interface idea. Sometimes, though, they're necessary to resolve ambiguities
598among similar interfaces.
599</p>
600
Rob Pike93c4a242011-08-06 07:41:55 +1000601<h3 id="t_and_equal_interface">
602Why doesn't type T satisfy the Equal interface?</h3>
603
604<p>
605Consider this simple interface to represent an object that can compare
606itself with another value:
607</p>
608
609<pre>
610type Equaler interface {
611 Equal(Equaler) bool
612}
613</pre>
614
615<p>
616and this type, <code>T</code>:
617</p>
618
619<pre>
620type T int
621func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
622</pre>
623
624<p>
625Unlike the analogous situation in some polymorphic type systems,
626<code>T</code> does not implement <code>Equaler</code>.
627The argument type of <code>T.Equal</code> is <code>T</code>,
628not literally the required type <code>Equaler</code>.
629</p>
630
631<p>
632In Go, the type system does not promote the argument of
633<code>Equal</code>; that is the programmer's responsibility, as
634illustrated by the type <code>T2</code>, which does implement
635<code>Equaler</code>:
636</p>
637
638<pre>
639type T2 int
640func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
641</pre>
642
643<p>
644Even this isn't like other type systems, though, because in Go <em>any</em>
645type that satisfies <code>Equaler</code> could be passed as the
646argument to <code>T2.Equal</code>, and at run time we must
647check that the argument is of type <code>T2</code>.
648Some languages arrange to make that guarantee at compile time.
649</p>
650
651<p>
652A related example goes the other way:
653</p>
654
655<pre>
656type Opener interface {
657 Open(name) Reader
658}
659
660func (t T3) Open() *os.File
661</pre>
662
663<p>
664In Go, <code>T3</code> does not satisfy <code>Opener</code>,
665although it might in another language.
666</p>
667
668<p>
669While it is true that Go's type system does less for the programmer
670in such cases, the lack of subtyping makes the rules about
671interface satisfaction very easy to state: are the function's names
672and signatures exactly those of the interface?
673Go's rule is also easy to implement efficiently.
674We feel these benefits offset the lack of
675automatic type promotion. Should Go one day adopt some form of generic
676typing, we expect there would be a way to express the idea of these
677examples and also have them be statically checked.
678</p>
679
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000680<h3 id="convert_slice_of_interface">
681Can I convert a []T to an []interface{}?</h3>
682
683<p>
684Not directly because they do not have the same representation in memory.
685It is necessary to copy the elements individually to the destination
686slice. This example converts a slice of <code>int</code> to a slice of
687<code>interface{}</code>:
688</p>
689
690<pre>
691t := []int{1, 2, 3, 4}
692s := make([]interface{}, len(t))
693for i, v := range t {
694 s[i] = v
695}
696</pre>
697
Rob Pike7d87f3d2011-08-06 11:21:59 +1000698<h3 id="unions">
699Why are there no untagged unions, as in C?</h3>
700
701<p>
702Untagged unions would violate Go's memory safety
703guarantees.
704</p>
705
706<h3 id="variant_types">
707Why does Go not have variant types?</h3>
708
709<p>
710Variant types, also known as algebraic types, provide a way to specify
711that a value might take one of a set of other types, but only those
712types. A common example in systems programming would specify that an
713error is, say, a network error, a security error or an application
714error and allow the caller to discriminate the source of the problem
715by examining the type of the error. Another example is a syntax tree
716in which each node can be a different type: declaration, statement,
717assignment and so on.
718</p>
719
720<p>
721We considered adding variant types to Go, but after discussion
722decided to leave them out because they overlap in confusing ways
723with interfaces. What would happen if the elements of a variant type
724were themselves interfaces?
725</p>
726
727<p>
728Also, some of what variant types address is already covered by the
729language. The error example is easy to express using an interface
730value to hold the error and a type switch to discriminate cases. The
731syntax tree example is also doable, although not as elegantly.
732</p>
733
Andrew Gerrand4164d602010-09-29 16:52:22 +1000734<h2 id="values">Values</h2>
735
736<h3 id="conversions">
737Why does Go not provide implicit numeric conversions?</h3>
738<p>
739The convenience of automatic conversion between numeric types in C is
740outweighed by the confusion it causes. When is an expression unsigned?
741How big is the value? Does it overflow? Is the result portable, independent
742of the machine on which it executes?
743It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
744are not easy to implement and inconsistent across architectures.
745For reasons of portability, we decided to make things clear and straightforward
746at the cost of some explicit conversions in the code.
747The definition of constants in Go&mdash;arbitrary precision values free
748of signedness and size annotations&mdash;ameliorates matters considerably,
749though.
750</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000751
Andrew Gerrand4164d602010-09-29 16:52:22 +1000752<p>
753A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
754are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
755type is generic; if you care about how many bits an integer holds, Go
756encourages you to be explicit.
757</p>
758
759<h3 id="builtin_maps">
760Why are maps built in?</h3>
761<p>
762The same reason strings are: they are such a powerful and important data
763structure that providing one excellent implementation with syntactic support
764makes programming more pleasant. We believe that Go's implementation of maps
765is strong enough that it will serve for the vast majority of uses.
766If a specific application can benefit from a custom implementation, it's possible
767to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
768</p>
769
Andrew Gerrand4164d602010-09-29 16:52:22 +1000770<h3 id="map_keys">
771Why don't maps allow structs and arrays as keys?</h3>
772<p>
773Map lookup requires an equality operator, which structs and arrays do not implement.
774They don't implement equality because equality is not well defined on such types;
775there are multiple considerations involving shallow vs. deep comparison, pointer vs.
776value comparison, how to deal with recursive structures, and so on.
777We may revisit this issue&mdash;and implementing equality for structs and arrays
778will not invalidate any existing programs&mdash;but without a clear idea of what
779equality of structs and arrays should mean, it was simpler to leave it out for now.
780</p>
781
782<h3 id="references">
783Why are maps, slices, and channels references while arrays are values?</h3>
784<p>
785There's a lot of history on that topic. Early on, maps and channels
786were syntactically pointers and it was impossible to declare or use a
787non-pointer instance. Also, we struggled with how arrays should work.
788Eventually we decided that the strict separation of pointers and
789values made the language harder to use. Introducing reference types,
790including slices to handle the reference form of arrays, resolved
791these issues. Reference types add some regrettable complexity to the
792language but they have a large effect on usability: Go became a more
793productive, comfortable language when they were introduced.
794</p>
795
Russ Cox32274452009-10-22 00:13:51 -0700796<h2 id="Writing_Code">Writing Code</h2>
797
798<h3 id="How_are_libraries_documented">
799How are libraries documented?</h3>
800
801<p>
802There is a program, <code>godoc</code>, written in Go, that extracts
803package documentation from the source code. It can be used on the
804command line or on the web. An instance is running at
Rob Pike0c2a4792009-11-01 20:50:42 -0800805<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -0800806In fact, <code>godoc</code> implements the full site at
Rob Pike0c2a4792009-11-01 20:50:42 -0800807<a href="http://golang.org/">http://golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000808</p>
Russ Cox32274452009-10-22 00:13:51 -0700809
810<h3 id="Is_there_a_Go_programming_style_guide">
811Is there a Go programming style guide?</h3>
812
813<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800814Eventually, there may be a small number of rules to guide things
815like naming, layout, and file organization.
816The document <a href="effective_go.html">Effective Go</a>
817contains some style advice.
818More directly, the program <code>gofmt</code> is a pretty-printer
819whose purpose is to enforce layout rules; it replaces the usual
820compendium of do's and don'ts that allows interpretation.
821All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +1000822</p>
Russ Cox32274452009-10-22 00:13:51 -0700823
824<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
825How do I submit patches to the Go libraries?</h3>
826
Rob Pike0c2a4792009-11-01 20:50:42 -0800827<p>
828The library sources are in <code>go/src/pkg</code>.
829If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +1000830</p>
Russ Cox32274452009-10-22 00:13:51 -0700831
Rob Pike0c2a4792009-11-01 20:50:42 -0800832<p>
833See the document
834<a href="contribute.html">Contributing to the Go project</a>
835for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +1000836</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000837
838<h2 id="Pointers">Pointers and Allocation</h2>
839
840<h3 id="pass_by_value">
841When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700842
843<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000844Everything in Go is passed by value. A function always gets a copy of the
845thing being passed, as if there were an assignment statement assigning the
846value to the parameter. For instance, copying a pointer value makes a copy of
847the pointer, not the data it points to.
848</p>
Russ Cox32274452009-10-22 00:13:51 -0700849
850<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000851Map and slice values behave like pointers; they are descriptors that
852contain pointers to the underlying map or slice data. Copying a map or
853slice value doesn't copy the data it points to. Copying an interface value
854makes a copy of the thing stored in the interface value. If the interface
855value holds a struct, copying the interface value makes a copy of the
856struct. If the interface value holds a pointer, copying the interface value
857makes a copy of the pointer, but again not the data it points to.
858</p>
859
860<h3 id="methods_on_values_or_pointers">
861Should I define methods on values or pointers?</h3>
862
863<pre>
Rob Pike93c4a242011-08-06 07:41:55 +1000864func (s *MyStruct) pointerMethod() { } // method on pointer
865func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +1000866</pre>
Russ Cox32274452009-10-22 00:13:51 -0700867
868<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000869For programmers unaccustomed to pointers, the distinction between these
870two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000871When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike93c4a242011-08-06 07:41:55 +1000872example) behaves exactly as if it were an argument to the method.
873Whether to define the receiver as a value or as a pointer is the same
874question, then, as whether a function argument should be a value or
875a pointer.
876There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000877</p>
878
Rob Pike93c4a242011-08-06 07:41:55 +1000879<p>
880First, and most important, does the method need to modify the
881receiver?
882If it does, the receiver <em>must</em> be a pointer.
883(Slices and maps are reference types, so their story is a little
884more subtle, but for instance to change the length of a slice
885in a method the receiver must still be a pointer.)
886In the examples above, if <code>pointerMethod</code> modifies
887the fields of <code>s</code>,
888the caller will see those changes, but <code>valueMethod</code>
889is called with a copy of the caller's argument (that's the definition
890of passing a value), so changes it makes will be invisible to the caller.
891</p>
892
893<p>
894By the way, pointer receivers are identical to the situation in Java,
895although in Java the pointers are hidden under the covers; it's Go's
896value receivers that are unusual.
897</p>
898
899<p>
900Second is the consideration of efficiency. If the receiver is large,
901a big <code>struct</code> for instance, it will be much cheaper to
902use a pointer receiver.
903</p>
904
905<p>
906Next is consistency. If some of the methods of the type must have
907pointer receivers, the rest should too, so the method set is
908consistent regardless of how the type is used.
909See the section on <a href="#different_method_sets">method sets</a>
910for details.
911</p>
912
913<p>
914For types such as basic types, slices, and small <code>structs</code>,
915a value receiver is very cheap so unless the semantics of the method
916requires a pointer, a value receiver is efficient and clear.
917</p>
918
919
Andrew Gerrand4164d602010-09-29 16:52:22 +1000920<h3 id="new_and_make">
921What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700922
923<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000924In short: <code>new</code> allocates memory, <code>make</code> initializes
925the slice, map, and channel types.
926</p>
927
928<p>
929See the <a href="/doc/effective_go.html#allocation_new">relevant section
930of Effective Go</a> for more details.
931</p>
932
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +1100933<h3 id="q_int_sizes">
Andrew Gerrand4164d602010-09-29 16:52:22 +1000934Why is <code>int</code> 32 bits on 64 bit machines?</h3>
935
936<p>
Rob Pike80e25fc2011-01-19 23:07:38 -0500937The sizes of <code>int</code> and <code>uint</code> are implementation-specific
938but the same as each other on a given platform.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000939The 64 bit Go compilers (both 6g and gccgo) use a 32 bit representation for
Rob Pike80e25fc2011-01-19 23:07:38 -0500940<code>int</code>. Code that relies on a particular
941size of value should use an explicitly sized type, like <code>int64</code>.
942On the other hand, floating-point scalars and complex
943numbers are always sized: <code>float32</code>, <code>complex64</code>,
944etc., because programmers should be aware of precision when using
945floating-point numbers.
946The default size of a floating-point constant is <code>float64</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000947</p>
948
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100949<h3 id="stack_or_heap">
950How do I know whether a variable is allocated on the heap or the stack?</h3>
951
952<p>
953From a correctness standpoint, you don't need to know.
954Each variable in Go exists as long as there are references to it.
955The storage location chosen by the implementation is irrelevant to the
956semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +1000957</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100958
959<p>
960The storage location does have an effect on writing efficient programs.
961When possible, the Go compilers will allocate variables that are
962local to a function in that function's stack frame. However, if the
963compiler cannot prove that the variable is not referenced after the
964function returns, then the compiler must allocate the variable on the
965garbage-collected heap to avoid dangling pointer errors.
Evan Shaw64d85762011-05-22 14:56:12 +1000966</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100967
968<p>
969In the current compilers, the analysis is crude: if a variable has its address
970taken, that variable is allocated on the heap. We are working to improve this
971analysis so that more data is kept on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +1000972</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100973
Andrew Gerrand4164d602010-09-29 16:52:22 +1000974<h2 id="Concurrency">Concurrency</h2>
975
976<h3 id="What_operations_are_atomic_What_about_mutexes">
977What operations are atomic? What about mutexes?</h3>
978
979<p>
980We haven't fully defined it all yet, but some details about atomicity are
981available in the <a href="go_mem.html">Go Memory Model specification</a>.
982</p>
983
984<p>
985Regarding mutexes, the <a href="/pkg/sync">sync</a>
986package implements them, but we hope Go programming style will
987encourage people to try higher-level techniques. In particular, consider
988structuring your program so that only one goroutine at a time is ever
989responsible for a particular piece of data.
990</p>
991
992<p>
993Do not communicate by sharing memory. Instead, share memory by communicating.
994</p>
995
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000996<p>
997See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk and its <a href="http://blog.golang.org/2010/07/share-memory-by-communicating.html">associated article</a> for a detailed discussion of this concept.
998</p>
999
Andrew Gerrand4164d602010-09-29 16:52:22 +10001000<h3 id="Why_no_multi_CPU">
1001Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1002
1003<p>
1004Under the gc compilers you must set <code>GOMAXPROCS</code> to allow the
Rob Pike966bf712011-03-01 13:54:22 -08001005run-time support to utilise more than one OS thread. Under <code>gccgo</code> an OS
Andrew Gerrand4164d602010-09-29 16:52:22 +10001006thread will be created for each goroutine, and <code>GOMAXPROCS</code> is
1007effectively equal to the number of running goroutines.
1008</p>
1009
1010<p>
1011Programs that perform concurrent computation should benefit from an increase in
1012<code>GOMAXPROCS</code>. (See the <a
Rob Pike966bf712011-03-01 13:54:22 -08001013href="http://golang.org/pkg/runtime/#GOMAXPROCS"><code>runtime</code> package's
Andrew Gerrand4164d602010-09-29 16:52:22 +10001014documentation</a>.)
1015</p>
1016
1017<h3 id="Why_GOMAXPROCS">
1018Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
1019slower?</h3>
1020
1021<p>
1022(This is specific to the gc compilers. See above.)
1023</p>
1024
1025<p>
1026It depends on the nature of your program.
1027Programs that contain several goroutines that spend a lot of time
1028communicating on channels will experience performance degradation when using
1029multiple OS threads. This is because of the significant context-switching
1030penalty involved in sending data between threads.
1031</p>
1032
1033<p>
Rob Pike966bf712011-03-01 13:54:22 -08001034Go's goroutine scheduler is not as good as it needs to be. In future, it
1035should recognize such cases and optimize its use of OS threads. For now,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001036<code>GOMAXPROCS</code> should be set on a per-application basis.
1037</p>
1038
Andrew Gerrand4164d602010-09-29 16:52:22 +10001039<h2 id="Functions_methods">Functions and Methods</h2>
1040
1041<h3 id="different_method_sets">
1042Why do T and *T have different method sets?</h3>
1043
1044<p>
1045From the <a href="http://golang.org/doc/go_spec.html#Types">Go Spec</a>:
1046</p>
1047
1048<blockquote>
1049The method set of any other named type <code>T</code> consists of all methods
1050with receiver type <code>T</code>. The method set of the corresponding pointer
1051type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1052<code>T</code> (that is, it also contains the method set of <code>T</code>).
1053</blockquote>
1054
1055<p>
1056If an interface value contains a pointer <code>*T</code>,
1057a method call can obtain a value by dereferencing the pointer,
1058but if an interface value contains a value <code>T</code>,
1059there is no useful way for a method call to obtain a pointer.
1060</p>
1061
1062<p>
1063If not for this restriction, this code:
1064</p>
1065
1066<pre>
1067var buf bytes.Buffer
1068io.Copy(buf, os.Stdin)
1069</pre>
1070
1071<p>
1072would copy standard input into a <i>copy</i> of <code>buf</code>,
1073not into <code>buf</code> itself.
1074This is almost never the desired behavior.
1075</p>
1076
1077<h3 id="closures_and_goroutines">
1078Why am I confused by the way my closures behave as goroutines?</h3>
1079
1080<p>
1081Some confusion may arise when using closures with concurrency.
1082Consider the following program:
1083</p>
1084
1085<pre>
1086func main() {
1087 done := make(chan bool)
1088
Rob Pikea64e6322011-01-26 10:41:32 -08001089 values := []string{ "a", "b", "c" }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001090 for _, v := range values {
1091 go func() {
1092 fmt.Println(v)
1093 done &lt;- true
1094 }()
1095 }
1096
1097 // wait for all goroutines to complete before exiting
Rob Pikea64e6322011-01-26 10:41:32 -08001098 for _ = range values {
Andrew Gerrand4164d602010-09-29 16:52:22 +10001099 &lt;-done
1100 }
1101}
1102</pre>
1103
1104<p>
1105One might mistakenly expect to see <code>a, b, c</code> as the output.
1106What you'll probably see instead is <code>c, c, c</code>. This is because
1107each closure shares the same variable <code>v</code>. Each closure prints the
1108value of <code>v</code> at the time <code>fmt.Println</code> is executed,
1109rather than the value of <code>v</code> when the goroutine was launched.
1110</p>
1111
1112<p>
1113To bind the value of <code>v</code> to each closure as they are launched, one
1114could modify the inner loop to read:
1115</p>
1116
1117<pre>
1118 for _, v := range values {
Rob Pikea64e6322011-01-26 10:41:32 -08001119 go func(<b>u</b> string) {
Andrew Gerrand4164d602010-09-29 16:52:22 +10001120 fmt.Println(<b>u</b>)
1121 done &lt;- true
1122 }(<b>v</b>)
1123 }
1124</pre>
1125
1126<p>
1127In this example, the value of <code>v</code> is passed as an argument to the
1128anonymous function. That value is then accessible inside the function as
1129the variable <code>u</code>.
1130</p>
1131
1132<h2 id="Control_flow">Control flow</h2>
1133
1134<h3 id="Does_Go_have_a_ternary_form">
1135Does Go have the <code>?:</code> operator?</h3>
1136
1137<p>
1138There is no ternary form in Go. You may use the following to achieve the same
1139result:
1140</p>
1141
1142<pre>
1143if expr {
1144 n = trueVal
1145} else {
1146 n = falseVal
1147}
1148</pre>
1149
1150<h2 id="Packages_Testing">Packages and Testing</h2>
1151
1152<h3 id="How_do_I_create_a_multifile_package">
1153How do I create a multifile package?</h3>
1154
1155<p>
1156Put all the source files for the package in a directory by themselves.
1157Source files can refer to items from different files at will; there is
1158no need for forward declarations or a header file.
1159</p>
1160
1161<p>
1162Other than being split into multiple files, the package will compile and test
1163just like a single-file package.
1164</p>
1165
1166<h3 id="How_do_I_write_a_unit_test">
1167How do I write a unit test?</h3>
1168
1169<p>
1170Create a new file ending in <code>_test.go</code> in the same directory
1171as your package sources. Inside that file, <code>import "testing"</code>
1172and write functions of the form
1173</p>
1174
1175<pre>
1176func TestFoo(t *testing.T) {
1177 ...
1178}
1179</pre>
1180
1181<p>
1182Run <code>gotest</code> in that directory.
1183That script finds the <code>Test</code> functions,
1184builds a test binary, and runs it.
1185</p>
1186
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001187<p>See the <a href="/doc/code.html">How to Write Go Code</a> document for more details.</p>
1188
Russ Cox32274452009-10-22 00:13:51 -07001189
1190<h2 id="Implementation">Implementation</h2>
1191
1192<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1193What compiler technology is used to build the compilers?</h3>
1194
1195<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001196<code>Gccgo</code> has a C++ front-end with a recursive descent parser coupled to the
1197standard GCC back end. <code>Gc</code> is written in C using
1198<code>yacc</code>/<code>bison</code> for the parser.
Russ Cox32274452009-10-22 00:13:51 -07001199Although it's a new program, it fits in the Plan 9 C compiler suite
1200(<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>)
1201and uses a variant of the Plan 9 loader to generate ELF binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001202</p>
Russ Cox32274452009-10-22 00:13:51 -07001203
1204<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001205We considered writing <code>6g</code>, the original Go compiler, in Go itself but
Russ Cox32274452009-10-22 00:13:51 -07001206elected not to do so because of the difficulties of bootstrapping and
Rob Pike0c2a4792009-11-01 20:50:42 -08001207especially of open source distribution&mdash;you'd need a Go compiler to
1208set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
1209consider writing a compiler in Go, which might well happen. (Go would be a
Russ Cox32274452009-10-22 00:13:51 -07001210fine language in which to implement a compiler; a native lexer and
Rob Pike0c2a4792009-11-01 20:50:42 -08001211parser are already available in <a href="/pkg/go/"><code>/pkg/go</code></a>.)
Evan Shaw64d85762011-05-22 14:56:12 +10001212</p>
Russ Cox32274452009-10-22 00:13:51 -07001213
1214<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001215We also considered using LLVM for <code>6g</code> but we felt it was too large and
Russ Cox32274452009-10-22 00:13:51 -07001216slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001217</p>
Russ Cox32274452009-10-22 00:13:51 -07001218
Rob Pike966bf712011-03-01 13:54:22 -08001219<h3 id="How_is_the_run_time_support_implemented">
1220How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001221
1222<p>
Rob Pike966bf712011-03-01 13:54:22 -08001223Again due to bootstrapping issues, the run-time code is mostly in C (with a
Russ Cox32274452009-10-22 00:13:51 -07001224tiny bit of assembler) although Go is capable of implementing most of
Rob Pike966bf712011-03-01 13:54:22 -08001225it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
David Symondsbe96fa52011-07-31 12:59:58 +10001226<code>Gc</code> uses a custom library to keep the footprint under
Rob Pike0c2a4792009-11-01 20:50:42 -08001227control; it is
1228compiled with a version of the Plan 9 C compiler that supports
1229segmented stacks for goroutines.
Russ Coxe434f1a2009-11-07 17:31:22 -08001230Work is underway to provide the same stack management in
Rob Pike0c2a4792009-11-01 20:50:42 -08001231<code>gccgo</code>.
Evan Shaw64d85762011-05-22 14:56:12 +10001232</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001233
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001234<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1235Why is my trivial program such a large binary?</h3>
1236
1237<p>
1238The gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>) only
1239generate statically linked binaries. All Go binaries therefore include the Go
1240run-time, along with the run-time type information necessary to support dynamic
1241type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001242</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001243
1244<p>
1245A trivial C "hello, world" program compiled and linked statically using gcc
Rob Pikece0de422011-03-08 11:47:41 -08001246on Linux is around 750 kB. An equivalent Go program is around 1.1 MB, but
Rob Pike966bf712011-03-01 13:54:22 -08001247that includes more powerful run-time support. We believe that with some effort
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001248the size of Go binaries can be reduced.
Evan Shaw64d85762011-05-22 14:56:12 +10001249</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001250
Rob Pike7d87f3d2011-08-06 11:21:59 +10001251<h3 id="unused_variables_and_imports">
1252Can I stop these complaints about my unused variable/import?</h3>
1253
1254<p>
1255The presence of an unused variable may indicate a bug, while
1256unused imports just slow down compilation.
1257Accumulate enough unused imports in your code tree and
1258things can get very slow.
1259For these reasons, Go allows neither.
1260</p>
1261
1262<p>
1263When developing code, it's common to create these situations
1264temporarily and it can be annoying to have to edit them out before the
1265program will compile.
1266</p>
1267
1268<p>
1269Some have asked for a compiler option to turn those checks off
1270or at least reduce them to warnings.
1271Such an option has not been added, though,
1272because compiler options should not affect the semantics of the
1273language and because the Go compiler does not report warnings, only
1274errors that prevent compilation.
1275</p>
1276
1277<p>
1278There are two reasons for having no warnings. First, if it's worth
1279complaining about, it's worth fixing in the code. (And if it's not
1280worth fixing, it's not worth mentioning.) Second, having the compiler
1281generate warnings encourages the implementation to warn about weak
1282cases that can make compilation noisy, masking real errors that
1283<em>should</em> be fixed.
1284</p>
1285
1286<p>
1287It's easy to address the situation, though. Use the blank identifier
1288to let unused things persist while you're developing.
1289</p>
1290
1291<pre>
1292import "unused"
1293
1294// This declaration marks the import as used by referencing an
1295// item from the package.
1296var _ = unused.Item // TODO: Delete before committing!
1297
1298func main() {
1299 debugData := debug.Profile()
1300 _ = debugData // Used only during debugging.
1301 ....
1302}
1303</pre>
1304
Andrew Gerrand08575732010-04-21 14:00:56 +10001305<h2 id="Performance">Performance</h2>
1306
1307<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1308Why does Go perform badly on benchmark X?</h3>
1309
1310<p>
1311One of Go's design goals is to approach the performance of C for comparable
1312programs, yet on some benchmarks it does quite poorly, including several
1313in <a href="/test/bench/">test/bench</a>. The slowest depend on libraries
1314for which versions of comparable performance are not available in Go.
1315For instance, pidigits depends on a multi-precision math package, and the C
1316versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
1317written in optimized assembler).
1318Benchmarks that depend on regular expressions (regex-dna, for instance) are
1319essentially comparing Go's stopgap <a href="/pkg/regexp">regexp package</a> to
1320mature, highly optimized regular expression libraries like PCRE.
1321</p>
1322
1323<p>
1324Benchmark games are won by extensive tuning and the Go versions of most
1325of the benchmarks need attention. If you measure comparable C
1326and Go programs (reverse-complement is one example), you'll see the two
1327languages are much closer in raw performance than this suite would
1328indicate.
1329</p>
1330
1331<p>
1332Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001333better, many libraries need major performance work, and the garbage collector
Andrew Gerrand08575732010-04-21 14:00:56 +10001334isn't fast enough yet (even if it were, taking care not to generate unnecessary
1335garbage can have a huge effect).
1336</p>
1337
Rob Pike93c4a242011-08-06 07:41:55 +10001338<p>
1339In any case, Go can often be very competitive. See the blog post about
1340<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1341Go programs</a> for an informative example.
1342
Andrew Gerrand4164d602010-09-29 16:52:22 +10001343<h2 id="change_from_c">Changes from C</h2>
1344
1345<h3 id="different_syntax">
1346Why is the syntax so different from C?</h3>
1347<p>
1348Other than declaration syntax, the differences are not major and stem
1349from two desires. First, the syntax should feel light, without too
1350many mandatory keywords, repetition, or arcana. Second, the language
1351has been designed to be easy to analyze
1352and can be parsed without a symbol table. This makes it much easier
1353to build tools such as debuggers, dependency analyzers, automated
1354documentation extractors, IDE plug-ins, and so on. C and its
1355descendants are notoriously difficult in this regard.
1356</p>
1357
1358<h3 id="declarations_backwards">
1359Why are declarations backwards?</h3>
1360<p>
1361They're only backwards if you're used to C. In C, the notion is that a
1362variable is declared like an expression denoting its type, which is a
1363nice idea, but the type and expression grammars don't mix very well and
1364the results can be confusing; consider function pointers. Go mostly
1365separates expression and type syntax and that simplifies things (using
1366prefix <code>*</code> for pointers is an exception that proves the rule). In C,
1367the declaration
1368</p>
1369<pre>
1370 int* a, b;
1371</pre>
1372<p>
1373declares <code>a</code> to be a pointer but not <code>b</code>; in Go
1374</p>
1375<pre>
1376 var a, b *int;
1377</pre>
1378<p>
1379declares both to be pointers. This is clearer and more regular.
1380Also, the <code>:=</code> short declaration form argues that a full variable
1381declaration should present the same order as <code>:=</code> so
1382</p>
1383<pre>
1384 var a uint64 = 1;
1385</pre>
1386has the same effect as
1387<pre>
1388 a := uint64(1);
1389</pre>
1390<p>
1391Parsing is also simplified by having a distinct grammar for types that
1392is not just the expression grammar; keywords such as <code>func</code>
1393and <code>chan</code> keep things clear.
1394</p>
1395
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001396<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001397See the article about
1398<a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a>
1399for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001400</p>
1401
Andrew Gerrand4164d602010-09-29 16:52:22 +10001402<h3 id="no_pointer_arithmetic">
1403Why is there no pointer arithmetic?</h3>
1404<p>
1405Safety. Without pointer arithmetic it's possible to create a
1406language that can never derive an illegal address that succeeds
1407incorrectly. Compiler and hardware technology have advanced to the
1408point where a loop using array indices can be as efficient as a loop
1409using pointer arithmetic. Also, the lack of pointer arithmetic can
1410simplify the implementation of the garbage collector.
1411</p>
1412
1413<h3 id="inc_dec">
1414Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
1415<p>
1416Without pointer arithmetic, the convenience value of pre- and postfix
1417increment operators drops. By removing them from the expression
1418hierarchy altogether, expression syntax is simplified and the messy
1419issues around order of evaluation of <code>++</code> and <code>--</code>
1420(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
1421are eliminated as well. The simplification is
1422significant. As for postfix vs. prefix, either would work fine but
1423the postfix version is more traditional; insistence on prefix arose
1424with the STL, a library for a language whose name contains, ironically, a
1425postfix increment.
1426</p>
1427
1428<h3 id="semicolons">
1429Why are there braces but no semicolons? And why can't I put the opening
1430brace on the next line?</h3>
1431<p>
1432Go uses brace brackets for statement grouping, a syntax familiar to
1433programmers who have worked with any language in the C family.
1434Semicolons, however, are for parsers, not for people, and we wanted to
1435eliminate them as much as possible. To achieve this goal, Go borrows
1436a trick from BCPL: the semicolons that separate statements are in the
1437formal grammar but are injected automatically, without lookahead, by
1438the lexer at the end of any line that could be the end of a statement.
1439This works very well in practice but has the effect that it forces a
1440brace style. For instance, the opening brace of a function cannot
1441appear on a line by itself.
1442</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001443
Andrew Gerrand4164d602010-09-29 16:52:22 +10001444<p>
1445Some have argued that the lexer should do lookahead to permit the
1446brace to live on the next line. We disagree. Since Go code is meant
1447to be formatted automatically by
1448<a href="http://golang.org/cmd/gofmt/"><code>gofmt</code></a>,
1449<i>some</i> style must be chosen. That style may differ from what
1450you've used in C or Java, but Go is a new language and
1451<code>gofmt</code>'s style is as good as any other. More
1452important&mdash;much more important&mdash;the advantages of a single,
1453programmatically mandated format for all Go programs greatly outweigh
1454any perceived disadvantages of the particular style.
1455Note too that Go's style means that an interactive implementation of
1456Go can use the standard syntax one line at a time without special rules.
1457</p>
1458
1459<h3 id="garbage_collection">
1460Why do garbage collection? Won't it be too expensive?</h3>
1461<p>
1462One of the biggest sources of bookkeeping in systems programs is
1463memory management. We feel it's critical to eliminate that
1464programmer overhead, and advances in garbage collection
1465technology in the last few years give us confidence that we can
1466implement it with low enough overhead and no significant
1467latency. (The current implementation is a plain mark-and-sweep
1468collector but a replacement is in the works.)
1469</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001470
Andrew Gerrand4164d602010-09-29 16:52:22 +10001471<p>
1472Another point is that a large part of the difficulty of concurrent
1473and multi-threaded programming is memory management;
1474as objects get passed among threads it becomes cumbersome
1475to guarantee they become freed safely.
1476Automatic garbage collection makes concurrent code far easier to write.
1477Of course, implementing garbage collection in a concurrent environment is
1478itself a challenge, but meeting it once rather than in every
1479program helps everyone.
1480</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001481
Andrew Gerrand4164d602010-09-29 16:52:22 +10001482<p>
1483Finally, concurrency aside, garbage collection makes interfaces
1484simpler because they don't need to specify how memory is managed across them.
1485</p>
Rob Pike93c4a242011-08-06 07:41:55 +10001486
1487<p>
1488On the topic of performance, keep in mind that Go gives the programmer
1489considerable control over memory layout and allocation, much more than
1490is typical in garbage-collected languages. A careful programmer can reduce
1491the garbage collection overhead dramatically by using the language well;
1492see the article about
1493<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1494Go programs</a> for a worked example, including a demonstration of Go's
1495profiling tools.
1496</p>