blob: 33e5cde41a16cab8a7eedcd0c6e50339ff9c2f2b [file] [log] [blame]
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11001<!--{
2 "Title": "FAQ"
3}-->
Russ Cox32274452009-10-22 00:13:51 -07004
5<h2 id="Origins">Origins</h2>
6
7<h3 id="What_is_the_purpose_of_the_project">
8What is the purpose of the project?</h3>
9
10<p>
11No major systems language has emerged in over a decade, but over that time
12the computing landscape has changed tremendously. There are several trends:
Rob Pike93c4a242011-08-06 07:41:55 +100013</p>
Russ Cox32274452009-10-22 00:13:51 -070014
15<ul>
16<li>
17Computers are enormously quicker but software development is not faster.
18<li>
19Dependency management is a big part of software development today but the
Russ Coxe434f1a2009-11-07 17:31:22 -080020&ldquo;header files&rdquo; of languages in the C tradition are antithetical to clean
Russ Cox32274452009-10-22 00:13:51 -070021dependency analysis&mdash;and fast compilation.
22<li>
23There is a growing rebellion against cumbersome type systems like those of
24Java and C++, pushing people towards dynamically typed languages such as
Rob Pike0c2a4792009-11-01 20:50:42 -080025Python and JavaScript.
Russ Cox32274452009-10-22 00:13:51 -070026<li>
27Some fundamental concepts such as garbage collection and parallel computation
28are not well supported by popular systems languages.
29<li>
30The emergence of multicore computers has generated worry and confusion.
31</ul>
32
33<p>
34We believe it's worth trying again with a new language, a concurrent,
35garbage-collected language with fast compilation. Regarding the points above:
Rob Pike93c4a242011-08-06 07:41:55 +100036</p>
Russ Cox32274452009-10-22 00:13:51 -070037
38<ul>
39<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080040It is possible to compile a large Go program in a few seconds on a single computer.
Russ Cox32274452009-10-22 00:13:51 -070041<li>
42Go provides a model for software construction that makes dependency
43analysis easy and avoids much of the overhead of C-style include files and
44libraries.
45<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080046Go's type system has no hierarchy, so no time is spent defining the
47relationships between types. Also, although Go has static types the language
Russ Cox32274452009-10-22 00:13:51 -070048attempts to make types feel lighter weight than in typical OO languages.
49<li>
50Go is fully garbage-collected and provides fundamental support for
51concurrent execution and communication.
52<li>
53By its design, Go proposes an approach for the construction of system
54software on multicore machines.
55</ul>
56
57<h3 id="What_is_the_origin_of_the_name">
58What is the origin of the name?</h3>
59
60<p>
Russ Coxe434f1a2009-11-07 17:31:22 -080061&ldquo;Ogle&rdquo; would be a good name for a Go debugger.
Evan Shaw64d85762011-05-22 14:56:12 +100062</p>
Russ Cox32274452009-10-22 00:13:51 -070063
Rob Pikebdecae92009-11-23 17:34:23 -080064<h3 id="Whats_the_origin_of_the_mascot">
65What's the origin of the mascot?</h3>
66
67<p>
68The mascot and logo were designed by
69<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
70<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
71the Plan 9 bunny.
72The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
73T-shirt design some years ago.
74The logo and mascot are covered by the
75<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
76license.
77</p>
78
Andrew Gerrand4164d602010-09-29 16:52:22 +100079<h3 id="What_kind_of_a_name_is_6g">
80What kind of a name is 6g?</h3>
81
82<p>
83The <code>6g</code> (and <code>8g</code> and <code>5g</code>) compiler is named in the
84tradition of the Plan 9 C compilers, described in
85<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">
86http://plan9.bell-labs.com/sys/doc/compiler.html</a>
87(see the table in section 2).
88
89<code>6</code> is the architecture letter for amd64 (or x86-64, if you prefer), while
90<code>g</code> stands for Go.
Evan Shaw64d85762011-05-22 14:56:12 +100091</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +100092
93<h3 id="history">
94What is the history of the project?</h3>
95<p>
96Robert Griesemer, Rob Pike and Ken Thompson started sketching the
97goals for a new language on the white board on September 21, 2007.
98Within a few days the goals had settled into a plan to do something
99and a fair idea of what it would be. Design continued part-time in
100parallel with unrelated work. By January 2008, Ken had started work
101on a compiler with which to explore ideas; it generated C code as its
102output. By mid-year the language had become a full-time project and
103had settled enough to attempt a production compiler. In May 2008,
104Ian Taylor independently started on a GCC front end for Go using the
105draft specification. Russ Cox joined in late 2008 and helped move the language
106and libraries from prototype to reality.
107</p>
108
109<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000110Go became a public open source project on November 10, 2009.
111Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000112</p>
113
Andrew Gerrand4164d602010-09-29 16:52:22 +1000114<h3 id="creating_a_new_language">
115Why are you creating a new language?</h3>
116<p>
117Go was born out of frustration with existing languages and
118environments for systems programming. Programming had become too
119difficult and the choice of languages was partly to blame. One had to
120choose either efficient compilation, efficient execution, or ease of
121programming; all three were not available in the same mainstream
122language. Programmers who could were choosing ease over
123safety and efficiency by moving to dynamically typed languages such as
124Python and JavaScript rather than C++ or, to a lesser extent, Java.
125</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000126
Andrew Gerrand4164d602010-09-29 16:52:22 +1000127<p>
128Go is an attempt to combine the ease of programming of an interpreted,
129dynamically typed
130language with the efficiency and safety of a statically typed, compiled language.
131It also aims to be modern, with support for networked and multicore
132computing. Finally, it is intended to be <i>fast</i>: it should take
133at most a few seconds to build a large executable on a single computer.
134To meet these goals required addressing a number of
135linguistic issues: an expressive but lightweight type system;
136concurrency and garbage collection; rigid dependency specification;
137and so on. These cannot be addressed well by libraries or tools; a new
138language was called for.
139</p>
140
Andrew Gerrand4164d602010-09-29 16:52:22 +1000141<h3 id="ancestors">
142What are Go's ancestors?</h3>
143<p>
144Go is mostly in the C family (basic syntax),
145with significant input from the Pascal/Modula/Oberon
146family (declarations, packages),
147plus some ideas from languages
148inspired by Tony Hoare's CSP,
149such as Newsqueak and Limbo (concurrency).
150However, it is a new language across the board.
151In every respect the language was designed by thinking
152about what programmers do and how to make programming, at least the
153kind of programming we do, more effective, which means more fun.
154</p>
155
Andrew Gerrand4164d602010-09-29 16:52:22 +1000156<h3 id="principles">
157What are the guiding principles in the design?</h3>
158<p>
159Programming today involves too much bookkeeping, repetition, and
160clerical work. As Dick Gabriel says, &ldquo;Old programs read
161like quiet conversations between a well-spoken research worker and a
162well-studied mechanical colleague, not as a debate with a compiler.
163Who'd have guessed sophistication bought such noise?&rdquo;
164The sophistication is worthwhile&mdash;no one wants to go back to
165the old languages&mdash;but can it be more quietly achieved?
166</p>
167<p>
168Go attempts to reduce the amount of typing in both senses of the word.
169Throughout its design, we have tried to reduce clutter and
170complexity. There are no forward declarations and no header files;
171everything is declared exactly once. Initialization is expressive,
172automatic, and easy to use. Syntax is clean and light on keywords.
173Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
174simple type derivation using the <code>:=</code>
175declare-and-initialize construct. And perhaps most radically, there
176is no type hierarchy: types just <i>are</i>, they don't have to
177announce their relationships. These simplifications allow Go to be
178expressive yet comprehensible without sacrificing, well, sophistication.
179</p>
180<p>
181Another important principle is to keep the concepts orthogonal.
182Methods can be implemented for any type; structures represent data while
183interfaces represent abstraction; and so on. Orthogonality makes it
184easier to understand what happens when things combine.
185</p>
186
Russ Cox32274452009-10-22 00:13:51 -0700187<h2 id="Usage">Usage</h2>
188
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000189<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800190
Evan Shaw64d85762011-05-22 14:56:12 +1000191<p>
192Yes. There are now several Go programs deployed in
Rob Pikefcfed142012-01-23 08:39:53 -0800193production inside Google. A public example is the server behind
194<a href="http://golang.org">http://golang.org</a>.
195It's just the <a href="/cmd/godoc"><code>godoc</code></a>
196document server running in a production configuration on
197<a href="http://code.google.com/appengine/">Google App Engine</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000198</p>
Rob Pike7685a672009-11-09 20:25:45 -0800199
Russ Cox32274452009-10-22 00:13:51 -0700200<h3 id="Do_Go_programs_link_with_Cpp_programs">
201Do Go programs link with C/C++ programs?</h3>
202
203<p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000204There are two Go compiler implementations, <code>6g</code> and friends,
205generically called <code>gc</code>, and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800206<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700207therefore only be linked with C programs using the same convention.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000208There is such a C compiler but no C++ compiler.
209<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
210GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000211</p>
Russ Cox32274452009-10-22 00:13:51 -0700212
213<p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000214The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
215&ldquo;foreign function interface&rdquo; to allow safe calling of
216C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000217</p>
218
Russ Cox32274452009-10-22 00:13:51 -0700219
Rob Pike0c2a4792009-11-01 20:50:42 -0800220<h3 id="Does_Go_support_Google_protocol_buffers">
221Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700222
223<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700224A separate open source project provides the necessary compiler plugin and library.
225It is available at
226<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
227</p>
Russ Cox32274452009-10-22 00:13:51 -0700228
Evan Shaw64d85762011-05-22 14:56:12 +1000229
Russ Cox6301fb42009-12-03 17:23:33 -0800230<h3 id="Can_I_translate_the_Go_home_page">
231Can I translate the Go home page into another language?</h3>
232
233<p>
234Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000235However, if you choose to add the Google logo or branding to your site
Russ Cox6301fb42009-12-03 17:23:33 -0800236(it does not appear on <a href="http://golang.org/">golang.org</a>),
237you will need to abide by the guidelines at
238<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
239</p>
240
Russ Cox32274452009-10-22 00:13:51 -0700241<h2 id="Design">Design</h2>
242
Andrew Gerrand4164d602010-09-29 16:52:22 +1000243<h3 id="unicode_identifiers">
244What's up with Unicode identifiers?</h3>
245
246<p>
247It was important to us to extend the space of identifiers from the
248confines of ASCII. Go's rule&mdash;identifier characters must be
249letters or digits as defined by Unicode&mdash;is simple to understand
250and to implement but has restrictions. Combining characters are
251excluded by design, for instance.
252Until there
253is an agreed external definition of what an identifier might be,
254plus a definition of canonicalization of identifiers that guarantees
255no ambiguity, it seemed better to keep combining characters out of
256the mix. Thus we have a simple rule that can be expanded later
257without breaking programs, one that avoids bugs that would surely arise
258from a rule that admits ambiguous identifiers.
259</p>
260
261<p>
262On a related note, since an exported identifier must begin with an
263upper-case letter, identifiers created from &ldquo;letters&rdquo;
264in some languages can, by definition, not be exported. For now the
265only solution is to use something like <code>X日本語</code>, which
266is clearly unsatisfactory; we are considering other options. The
267case-for-visibility rule is unlikely to change however; it's one
268of our favorite features of Go.
269</p>
270
271<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700272
273<p>
274Every language contains novel features and omits someone's favorite
275feature. Go was designed with an eye on felicity of programming, speed of
276compilation, orthogonality of concepts, and the need to support features
277such as concurrency and garbage collection. Your favorite feature may be
278missing because it doesn't fit, because it affects compilation speed or
279clarity of design, or because it would make the fundamental system model
280too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000281</p>
Russ Cox32274452009-10-22 00:13:51 -0700282
283<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800284If it bothers you that Go is missing feature <var>X</var>,
285please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700286they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000287</p>
Russ Cox32274452009-10-22 00:13:51 -0700288
Andrew Gerrand4164d602010-09-29 16:52:22 +1000289<h3 id="generics">
290Why does Go not have generic types?</h3>
291<p>
292Generics may well be added at some point. We don't feel an urgency for
293them, although we understand some programmers do.
294</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000295
Andrew Gerrand4164d602010-09-29 16:52:22 +1000296<p>
297Generics are convenient but they come at a cost in
298complexity in the type system and run-time. We haven't yet found a
299design that gives value proportionate to the complexity, although we
300continue to think about it. Meanwhile, Go's built-in maps and slices,
301plus the ability to use the empty interface to construct containers
302(with explicit unboxing) mean in many cases it is possible to write
303code that does what generics would enable, if less smoothly.
304</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000305
Andrew Gerrand4164d602010-09-29 16:52:22 +1000306<p>
307This remains an open issue.
308</p>
309
310<h3 id="exceptions">
311Why does Go not have exceptions?</h3>
312<p>
313We believe that coupling exceptions to a control
314structure, as in the <code>try-catch-finally</code> idiom, results in
315convoluted code. It also tends to encourage programmers to label
316too many ordinary errors, such as failing to open a file, as
317exceptional.
318</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000319
Andrew Gerrand4164d602010-09-29 16:52:22 +1000320<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000321Go takes a different approach. For plain error handling, Go's multi-value
322returns make it easy to report an error without overloading the return value.
323<a href="http://blog.golang.org/2011/07/error-handling-and-go.html">A
324canonical error type, coupled
325with Go's other features</a>, makes error
326handling pleasant but quite different from that in other languages.
327</p>
328
329<p>
330Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000331of built-in functions to signal and recover from truly exceptional
332conditions. The recovery mechanism is executed only as part of a
333function's state being torn down after an error, which is sufficient
334to handle catastrophe but requires no extra control structures and,
335when used well, can result in clean error-handling code.
336</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000337
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000338<p>
339See the <a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a> article for details.
340</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000341
Andrew Gerrand4164d602010-09-29 16:52:22 +1000342<h3 id="assertions">
343Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700344
345<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000346Go doesn't provide assertions. They are undeniably convenient, but our
347experience has been that programmers use them as a crutch to avoid thinking
348about proper error handling and reporting. Proper error handling means that
349servers continue operation after non-fatal errors instead of crashing.
350Proper error reporting means that errors are direct and to the point,
351saving the programmer from interpreting a large crash trace. Precise
352errors are particularly important when the programmer seeing the errors is
353not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000354</p>
Russ Cox32274452009-10-22 00:13:51 -0700355
Andrew Gerrand4164d602010-09-29 16:52:22 +1000356<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000357We understand that this is a point of contention. There are many things in
358the Go language and libraries that differ from modern practices, simply
359because we feel it's sometimes worth trying a different approach.
Evan Shaw64d85762011-05-22 14:56:12 +1000360</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000361
362<h3 id="csp">
363Why build concurrency on the ideas of CSP?</h3>
364<p>
365Concurrency and multi-threaded programming have a reputation
Rob Pikefcfed142012-01-23 08:39:53 -0800366for difficulty. We believe this is due partly to complex
Andrew Gerrand4164d602010-09-29 16:52:22 +1000367designs such as pthreads and partly to overemphasis on low-level details
Rob Pike93c4a242011-08-06 07:41:55 +1000368such as mutexes, condition variables, and memory barriers.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000369Higher-level interfaces enable much simpler code, even if there are still
370mutexes and such under the covers.
371</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000372
Andrew Gerrand4164d602010-09-29 16:52:22 +1000373<p>
374One of the most successful models for providing high-level linguistic support
375for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
376Occam and Erlang are two well known languages that stem from CSP.
377Go's concurrency primitives derive from a different part of the family tree
378whose main contribution is the powerful notion of channels as first class objects.
379</p>
380
381<h3 id="goroutines">
382Why goroutines instead of threads?</h3>
383<p>
384Goroutines are part of making concurrency easy to use. The idea, which has
385been around for a while, is to multiplex independently executing
Rob Pike93c4a242011-08-06 07:41:55 +1000386functions&mdash;coroutines&mdash;onto a set of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000387When a coroutine blocks, such as by calling a blocking system call,
388the run-time automatically moves other coroutines on the same operating
389system thread to a different, runnable thread so they won't be blocked.
390The programmer sees none of this, which is the point.
391The result, which we call goroutines, can be very cheap: unless they spend a lot of time
392in long-running system calls, they cost little more than the memory
Rob Pike93c4a242011-08-06 07:41:55 +1000393for the stack, which is just a few kilobytes.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000394</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000395
Andrew Gerrand4164d602010-09-29 16:52:22 +1000396<p>
397To make the stacks small, Go's run-time uses segmented stacks. A newly
398minted goroutine is given a few kilobytes, which is almost always enough.
399When it isn't, the run-time allocates (and frees) extension segments automatically.
400The overhead averages about three cheap instructions per function call.
401It is practical to create hundreds of thousands of goroutines in the same
402address space. If goroutines were just threads, system resources would
403run out at a much smaller number.
404</p>
405
406<h3 id="atomic_maps">
407Why are map operations not defined to be atomic?</h3>
408
409<p>
410After long discussion it was decided that the typical use of maps did not require
411safe access from multiple threads, and in those cases where it did, the map was
412probably part of some larger data structure or computation that was already
413synchronized. Therefore requiring that all map operations grab a mutex would slow
414down most programs and add safety to few. This was not an easy decision,
415however, since it means uncontrolled map access can crash the program.
416</p>
417
418<p>
419The language does not preclude atomic map updates. When required, such
420as when hosting an untrusted program, the implementation could interlock
421map access.
422</p>
423
Andrew Gerrand4164d602010-09-29 16:52:22 +1000424<h2 id="types">Types</h2>
Russ Cox32274452009-10-22 00:13:51 -0700425
426<h3 id="Is_Go_an_object-oriented_language">
427Is Go an object-oriented language?</h3>
428
429<p>
430Yes and no. Although Go has types and methods and allows an
431object-oriented style of programming, there is no type hierarchy.
Russ Coxe434f1a2009-11-07 17:31:22 -0800432The concept of &ldquo;interface&rdquo; in Go provides a different approach that
Russ Cox32274452009-10-22 00:13:51 -0700433we believe is easy to use and in some ways more general. There are
434also ways to embed types in other types to provide something
435analogous&mdash;but not identical&mdash;to subclassing.
Rob Pike0c2a4792009-11-01 20:50:42 -0800436Moreover, methods in Go are more general than in C++ or Java:
Rob Pikefcfed142012-01-23 08:39:53 -0800437they can be defined for any sort of data, even built-in types such
438as plain, &ldquo;unboxed&rdquo; integers.
439They are not restricted to structs (classes).
Evan Shaw64d85762011-05-22 14:56:12 +1000440</p>
Russ Cox32274452009-10-22 00:13:51 -0700441
442<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800443Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800444lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000445</p>
Russ Cox32274452009-10-22 00:13:51 -0700446
447<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
448How do I get dynamic dispatch of methods?</h3>
449
450<p>
451The only way to have dynamically dispatched methods is through an
Rob Pikefcfed142012-01-23 08:39:53 -0800452interface. Methods on a struct or any other concrete type are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000453</p>
Russ Cox32274452009-10-22 00:13:51 -0700454
Andrew Gerrand4164d602010-09-29 16:52:22 +1000455<h3 id="inheritance">
456Why is there no type inheritance?</h3>
457<p>
458Object-oriented programming, at least in the best-known languages,
459involves too much discussion of the relationships between types,
460relationships that often could be derived automatically. Go takes a
461different approach.
462</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000463
Andrew Gerrand4164d602010-09-29 16:52:22 +1000464<p>
465Rather than requiring the programmer to declare ahead of time that two
466types are related, in Go a type automatically satisfies any interface
467that specifies a subset of its methods. Besides reducing the
468bookkeeping, this approach has real advantages. Types can satisfy
469many interfaces at once, without the complexities of traditional
470multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000471Interfaces can be very lightweight&mdash;an interface with
472one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000473Interfaces can be added after the fact if a new idea comes along
474or for testing&mdash;without annotating the original types.
475Because there are no explicit relationships between types
476and interfaces, there is no type hierarchy to manage or discuss.
477</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000478
Andrew Gerrand4164d602010-09-29 16:52:22 +1000479<p>
480It's possible to use these ideas to construct something analogous to
481type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
482enables formatted printing to any output, not just a file, or how the
483<code>bufio</code> package can be completely separate from file I/O,
Rob Pike86494442011-11-08 16:26:03 -0800484or how the <code>image</code> packages generate compressed
485image files. All these ideas stem from a single interface
Andrew Gerrand4164d602010-09-29 16:52:22 +1000486(<code>io.Writer</code>) representing a single method
487(<code>Write</code>). And that's only scratching the surface.
488</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000489
Andrew Gerrand4164d602010-09-29 16:52:22 +1000490<p>
491It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000492dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000493</p>
494
495<h3 id="methods_on_basics">
496Why is <code>len</code> a function and not a method?</h3>
497<p>
498We debated this issue but decided
499implementing <code>len</code> and friends as functions was fine in practice and
500didn't complicate questions about the interface (in the Go type sense)
501of basic types.
502</p>
503
504<h3 id="overloading">
505Why does Go not support overloading of methods and operators?</h3>
506<p>
507Method dispatch is simplified if it doesn't need to do type matching as well.
508Experience with other languages told us that having a variety of
509methods with the same name but different signatures was occasionally useful
510but that it could also be confusing and fragile in practice. Matching only by name
511and requiring consistency in the types was a major simplifying decision
512in Go's type system.
513</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000514
Andrew Gerrand4164d602010-09-29 16:52:22 +1000515<p>
516Regarding operator overloading, it seems more a convenience than an absolute
517requirement. Again, things are simpler without it.
518</p>
519
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100520<h3 id="implements_interface">
521Why doesn't Go have "implements" declarations?</h3>
522
523<p>
524A Go type satisfies an interface by implementing the methods of that interface,
525nothing more. This property allows interfaces to be defined and used without
526having to modify existing code. It enables a kind of "duck typing" that
527promotes separation of concerns and improves code re-use, and makes it easier
528to build on patterns that emerge as the code develops.
529The semantics of interfaces is one of the main reasons for Go's nimble,
530lightweight feel.
531</p>
532
533<p>
534See the <a href="#inheritance">question on type inheritance</a> for more detail.
535</p>
536
537<h3 id="guarantee_satisfies_interface">
538How can I guarantee my type satisfies an interface?</h3>
539
540<p>
541You can ask the compiler to check that the type <code>T</code> implements the
542interface <code>I</code> by attempting an assignment:
543</p>
544
545<pre>
546type T struct{}
Rob Pikefcfed142012-01-23 08:39:53 -0800547var _ I = T{} // Verify that T implements I.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100548</pre>
549
550<p>
551If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
552at compile time.
553</p>
554
555<p>
556If you wish the users of an interface to explicitly declare that they implement
557it, you can add a method with a descriptive name to the interface's method set.
558For example:
559</p>
560
561<pre>
562type Fooer interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800563 Foo()
564 ImplementsFooer()
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100565}
566</pre>
567
568<p>
569A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100570<code>Fooer</code>, clearly documenting the fact and announcing it in
571<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100572</p>
573
574<pre>
575type Bar struct{}
576func (b Bar) ImplementsFooer() {}
577func (b Bar) Foo() {}
578</pre>
579
580<p>
581Most code doesn't make use of such constraints, since they limit the utility of
582the interface idea. Sometimes, though, they're necessary to resolve ambiguities
583among similar interfaces.
584</p>
585
Rob Pike93c4a242011-08-06 07:41:55 +1000586<h3 id="t_and_equal_interface">
587Why doesn't type T satisfy the Equal interface?</h3>
588
589<p>
590Consider this simple interface to represent an object that can compare
591itself with another value:
592</p>
593
594<pre>
595type Equaler interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800596 Equal(Equaler) bool
Rob Pike93c4a242011-08-06 07:41:55 +1000597}
598</pre>
599
600<p>
601and this type, <code>T</code>:
602</p>
603
604<pre>
605type T int
606func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
607</pre>
608
609<p>
610Unlike the analogous situation in some polymorphic type systems,
611<code>T</code> does not implement <code>Equaler</code>.
612The argument type of <code>T.Equal</code> is <code>T</code>,
613not literally the required type <code>Equaler</code>.
614</p>
615
616<p>
617In Go, the type system does not promote the argument of
618<code>Equal</code>; that is the programmer's responsibility, as
619illustrated by the type <code>T2</code>, which does implement
620<code>Equaler</code>:
621</p>
622
623<pre>
624type T2 int
625func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
626</pre>
627
628<p>
629Even this isn't like other type systems, though, because in Go <em>any</em>
630type that satisfies <code>Equaler</code> could be passed as the
631argument to <code>T2.Equal</code>, and at run time we must
632check that the argument is of type <code>T2</code>.
633Some languages arrange to make that guarantee at compile time.
634</p>
635
636<p>
637A related example goes the other way:
638</p>
639
640<pre>
641type Opener interface {
642 Open(name) Reader
643}
644
645func (t T3) Open() *os.File
646</pre>
647
648<p>
649In Go, <code>T3</code> does not satisfy <code>Opener</code>,
650although it might in another language.
651</p>
652
653<p>
654While it is true that Go's type system does less for the programmer
655in such cases, the lack of subtyping makes the rules about
656interface satisfaction very easy to state: are the function's names
657and signatures exactly those of the interface?
658Go's rule is also easy to implement efficiently.
659We feel these benefits offset the lack of
660automatic type promotion. Should Go one day adopt some form of generic
661typing, we expect there would be a way to express the idea of these
662examples and also have them be statically checked.
663</p>
664
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000665<h3 id="convert_slice_of_interface">
666Can I convert a []T to an []interface{}?</h3>
667
668<p>
Rob Pike86494442011-11-08 16:26:03 -0800669Not directly, because they do not have the same representation in memory.
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000670It is necessary to copy the elements individually to the destination
671slice. This example converts a slice of <code>int</code> to a slice of
672<code>interface{}</code>:
673</p>
674
675<pre>
676t := []int{1, 2, 3, 4}
677s := make([]interface{}, len(t))
678for i, v := range t {
Rob Pikefcfed142012-01-23 08:39:53 -0800679 s[i] = v
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000680}
681</pre>
682
Rob Pike7d87f3d2011-08-06 11:21:59 +1000683<h3 id="unions">
684Why are there no untagged unions, as in C?</h3>
685
686<p>
687Untagged unions would violate Go's memory safety
688guarantees.
689</p>
690
691<h3 id="variant_types">
692Why does Go not have variant types?</h3>
693
694<p>
695Variant types, also known as algebraic types, provide a way to specify
696that a value might take one of a set of other types, but only those
697types. A common example in systems programming would specify that an
698error is, say, a network error, a security error or an application
699error and allow the caller to discriminate the source of the problem
700by examining the type of the error. Another example is a syntax tree
701in which each node can be a different type: declaration, statement,
702assignment and so on.
703</p>
704
705<p>
706We considered adding variant types to Go, but after discussion
707decided to leave them out because they overlap in confusing ways
708with interfaces. What would happen if the elements of a variant type
709were themselves interfaces?
710</p>
711
712<p>
713Also, some of what variant types address is already covered by the
714language. The error example is easy to express using an interface
715value to hold the error and a type switch to discriminate cases. The
716syntax tree example is also doable, although not as elegantly.
717</p>
718
Andrew Gerrand4164d602010-09-29 16:52:22 +1000719<h2 id="values">Values</h2>
720
721<h3 id="conversions">
722Why does Go not provide implicit numeric conversions?</h3>
723<p>
724The convenience of automatic conversion between numeric types in C is
725outweighed by the confusion it causes. When is an expression unsigned?
726How big is the value? Does it overflow? Is the result portable, independent
727of the machine on which it executes?
728It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
729are not easy to implement and inconsistent across architectures.
730For reasons of portability, we decided to make things clear and straightforward
731at the cost of some explicit conversions in the code.
732The definition of constants in Go&mdash;arbitrary precision values free
733of signedness and size annotations&mdash;ameliorates matters considerably,
734though.
735</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000736
Andrew Gerrand4164d602010-09-29 16:52:22 +1000737<p>
738A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
739are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
740type is generic; if you care about how many bits an integer holds, Go
741encourages you to be explicit.
742</p>
743
744<h3 id="builtin_maps">
745Why are maps built in?</h3>
746<p>
747The same reason strings are: they are such a powerful and important data
748structure that providing one excellent implementation with syntactic support
749makes programming more pleasant. We believe that Go's implementation of maps
750is strong enough that it will serve for the vast majority of uses.
751If a specific application can benefit from a custom implementation, it's possible
752to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
753</p>
754
Andrew Gerrand4164d602010-09-29 16:52:22 +1000755<h3 id="map_keys">
Rob Pikefcfed142012-01-23 08:39:53 -0800756Why don't maps allow slices as keys?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000757<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800758Map lookup requires an equality operator, which slices do not implement.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000759They don't implement equality because equality is not well defined on such types;
760there are multiple considerations involving shallow vs. deep comparison, pointer vs.
Rob Pikefcfed142012-01-23 08:39:53 -0800761value comparison, how to deal with recursive types, and so on.
762We may revisit this issue&mdash;and implementing equality for slices
Andrew Gerrand4164d602010-09-29 16:52:22 +1000763will not invalidate any existing programs&mdash;but without a clear idea of what
764equality of structs and arrays should mean, it was simpler to leave it out for now.
765</p>
766
Rob Pikefcfed142012-01-23 08:39:53 -0800767<p>
768In Go 1, equality is defined for structs and arrays, so such
769types can be used as map keys, but slices still do not have a definition of equality.
770</p>
771
Andrew Gerrand4164d602010-09-29 16:52:22 +1000772<h3 id="references">
773Why are maps, slices, and channels references while arrays are values?</h3>
774<p>
775There's a lot of history on that topic. Early on, maps and channels
776were syntactically pointers and it was impossible to declare or use a
777non-pointer instance. Also, we struggled with how arrays should work.
778Eventually we decided that the strict separation of pointers and
779values made the language harder to use. Introducing reference types,
780including slices to handle the reference form of arrays, resolved
781these issues. Reference types add some regrettable complexity to the
782language but they have a large effect on usability: Go became a more
783productive, comfortable language when they were introduced.
784</p>
785
Russ Cox32274452009-10-22 00:13:51 -0700786<h2 id="Writing_Code">Writing Code</h2>
787
788<h3 id="How_are_libraries_documented">
789How are libraries documented?</h3>
790
791<p>
792There is a program, <code>godoc</code>, written in Go, that extracts
793package documentation from the source code. It can be used on the
794command line or on the web. An instance is running at
Rob Pike0c2a4792009-11-01 20:50:42 -0800795<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -0800796In fact, <code>godoc</code> implements the full site at
Rob Pike0c2a4792009-11-01 20:50:42 -0800797<a href="http://golang.org/">http://golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000798</p>
Russ Cox32274452009-10-22 00:13:51 -0700799
800<h3 id="Is_there_a_Go_programming_style_guide">
801Is there a Go programming style guide?</h3>
802
803<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800804Eventually, there may be a small number of rules to guide things
805like naming, layout, and file organization.
806The document <a href="effective_go.html">Effective Go</a>
807contains some style advice.
808More directly, the program <code>gofmt</code> is a pretty-printer
809whose purpose is to enforce layout rules; it replaces the usual
810compendium of do's and don'ts that allows interpretation.
811All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +1000812</p>
Russ Cox32274452009-10-22 00:13:51 -0700813
814<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
815How do I submit patches to the Go libraries?</h3>
816
Rob Pike0c2a4792009-11-01 20:50:42 -0800817<p>
818The library sources are in <code>go/src/pkg</code>.
819If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +1000820</p>
Russ Cox32274452009-10-22 00:13:51 -0700821
Rob Pike0c2a4792009-11-01 20:50:42 -0800822<p>
823See the document
824<a href="contribute.html">Contributing to the Go project</a>
825for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +1000826</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000827
828<h2 id="Pointers">Pointers and Allocation</h2>
829
830<h3 id="pass_by_value">
831When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700832
833<p>
Rob Pike86494442011-11-08 16:26:03 -0800834As in all languages in the C family, everything in Go is passed by value.
835That is, a function always gets a copy of the
Andrew Gerrand4164d602010-09-29 16:52:22 +1000836thing being passed, as if there were an assignment statement assigning the
Rob Pike86494442011-11-08 16:26:03 -0800837value to the parameter. For instance, passing an <code>int</code> value
838to a function makes a copy of the <code>int</code>, and passing a pointer
839value makes a copy of the pointer, but not the data it points to.
840(See the next section for a discussion of how this affects method receivers.)
Andrew Gerrand4164d602010-09-29 16:52:22 +1000841</p>
Russ Cox32274452009-10-22 00:13:51 -0700842
843<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800844Map and slice values behave like pointers: they are descriptors that
Andrew Gerrand4164d602010-09-29 16:52:22 +1000845contain pointers to the underlying map or slice data. Copying a map or
846slice value doesn't copy the data it points to. Copying an interface value
847makes a copy of the thing stored in the interface value. If the interface
848value holds a struct, copying the interface value makes a copy of the
849struct. If the interface value holds a pointer, copying the interface value
850makes a copy of the pointer, but again not the data it points to.
851</p>
852
853<h3 id="methods_on_values_or_pointers">
854Should I define methods on values or pointers?</h3>
855
856<pre>
Rob Pike93c4a242011-08-06 07:41:55 +1000857func (s *MyStruct) pointerMethod() { } // method on pointer
858func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +1000859</pre>
Russ Cox32274452009-10-22 00:13:51 -0700860
861<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000862For programmers unaccustomed to pointers, the distinction between these
863two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000864When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike93c4a242011-08-06 07:41:55 +1000865example) behaves exactly as if it were an argument to the method.
866Whether to define the receiver as a value or as a pointer is the same
867question, then, as whether a function argument should be a value or
868a pointer.
869There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000870</p>
871
Rob Pike93c4a242011-08-06 07:41:55 +1000872<p>
873First, and most important, does the method need to modify the
874receiver?
875If it does, the receiver <em>must</em> be a pointer.
876(Slices and maps are reference types, so their story is a little
877more subtle, but for instance to change the length of a slice
878in a method the receiver must still be a pointer.)
879In the examples above, if <code>pointerMethod</code> modifies
880the fields of <code>s</code>,
881the caller will see those changes, but <code>valueMethod</code>
882is called with a copy of the caller's argument (that's the definition
883of passing a value), so changes it makes will be invisible to the caller.
884</p>
885
886<p>
887By the way, pointer receivers are identical to the situation in Java,
888although in Java the pointers are hidden under the covers; it's Go's
889value receivers that are unusual.
890</p>
891
892<p>
893Second is the consideration of efficiency. If the receiver is large,
894a big <code>struct</code> for instance, it will be much cheaper to
895use a pointer receiver.
896</p>
897
898<p>
899Next is consistency. If some of the methods of the type must have
900pointer receivers, the rest should too, so the method set is
901consistent regardless of how the type is used.
902See the section on <a href="#different_method_sets">method sets</a>
903for details.
904</p>
905
906<p>
907For types such as basic types, slices, and small <code>structs</code>,
908a value receiver is very cheap so unless the semantics of the method
909requires a pointer, a value receiver is efficient and clear.
910</p>
911
912
Andrew Gerrand4164d602010-09-29 16:52:22 +1000913<h3 id="new_and_make">
914What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700915
916<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000917In short: <code>new</code> allocates memory, <code>make</code> initializes
918the slice, map, and channel types.
919</p>
920
921<p>
922See the <a href="/doc/effective_go.html#allocation_new">relevant section
923of Effective Go</a> for more details.
924</p>
925
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +1100926<h3 id="q_int_sizes">
Andrew Gerrand4164d602010-09-29 16:52:22 +1000927Why is <code>int</code> 32 bits on 64 bit machines?</h3>
928
929<p>
Rob Pike80e25fc2011-01-19 23:07:38 -0500930The sizes of <code>int</code> and <code>uint</code> are implementation-specific
931but the same as each other on a given platform.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000932The 64 bit Go compilers (both 6g and gccgo) use a 32 bit representation for
Rob Pike80e25fc2011-01-19 23:07:38 -0500933<code>int</code>. Code that relies on a particular
934size of value should use an explicitly sized type, like <code>int64</code>.
935On the other hand, floating-point scalars and complex
936numbers are always sized: <code>float32</code>, <code>complex64</code>,
937etc., because programmers should be aware of precision when using
938floating-point numbers.
939The default size of a floating-point constant is <code>float64</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000940</p>
941
Rob Pike86494442011-11-08 16:26:03 -0800942<p>
943At the moment, all implementations use 32-bit ints, an essentially arbitrary decision.
944However, we expect that <code>int</code> will be increased to 64 bits on 64-bit
945architectures in a future release of Go.
946</p>
947
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100948<h3 id="stack_or_heap">
949How do I know whether a variable is allocated on the heap or the stack?</h3>
950
951<p>
952From a correctness standpoint, you don't need to know.
953Each variable in Go exists as long as there are references to it.
954The storage location chosen by the implementation is irrelevant to the
955semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +1000956</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100957
958<p>
959The storage location does have an effect on writing efficient programs.
960When possible, the Go compilers will allocate variables that are
961local to a function in that function's stack frame. However, if the
962compiler cannot prove that the variable is not referenced after the
963function returns, then the compiler must allocate the variable on the
964garbage-collected heap to avoid dangling pointer errors.
Rob Pikefcfed142012-01-23 08:39:53 -0800965Also, if a local variable is very large, it might make more sense
966to store it on the heap rather than the stack.
Evan Shaw64d85762011-05-22 14:56:12 +1000967</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100968
969<p>
Rob Pike86494442011-11-08 16:26:03 -0800970In the current compilers, if a variable has its address taken, that variable
971is a candidate for allocation on the heap. However, a basic <em>escape
972analysis</em> recognizes some cases when such variables will not
973live past the return from the function and can reside on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +1000974</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +1100975
Andrew Gerrand4164d602010-09-29 16:52:22 +1000976<h2 id="Concurrency">Concurrency</h2>
977
978<h3 id="What_operations_are_atomic_What_about_mutexes">
979What operations are atomic? What about mutexes?</h3>
980
981<p>
982We haven't fully defined it all yet, but some details about atomicity are
983available in the <a href="go_mem.html">Go Memory Model specification</a>.
984</p>
985
986<p>
987Regarding mutexes, the <a href="/pkg/sync">sync</a>
988package implements them, but we hope Go programming style will
989encourage people to try higher-level techniques. In particular, consider
990structuring your program so that only one goroutine at a time is ever
991responsible for a particular piece of data.
992</p>
993
994<p>
995Do not communicate by sharing memory. Instead, share memory by communicating.
996</p>
997
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000998<p>
999See 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.
1000</p>
1001
Andrew Gerrand4164d602010-09-29 16:52:22 +10001002<h3 id="Why_no_multi_CPU">
1003Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1004
1005<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001006You must set <code>GOMAXPROCS</code> to allow the
1007run-time support to utilize more than one OS thread.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001008</p>
1009
1010<p>
Rob Pike86494442011-11-08 16:26:03 -08001011Programs that perform parallel computation should benefit from an increase in
Andrew Gerrand4164d602010-09-29 16:52:22 +10001012<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>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001022It depends on the nature of your program.
1023Programs that contain several goroutines that spend a lot of time
1024communicating on channels will experience performance degradation when using
1025multiple OS threads. This is because of the significant context-switching
1026penalty involved in sending data between threads.
1027</p>
1028
1029<p>
Rob Pike966bf712011-03-01 13:54:22 -08001030Go's goroutine scheduler is not as good as it needs to be. In future, it
1031should recognize such cases and optimize its use of OS threads. For now,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001032<code>GOMAXPROCS</code> should be set on a per-application basis.
1033</p>
1034
Andrew Gerrand4164d602010-09-29 16:52:22 +10001035<h2 id="Functions_methods">Functions and Methods</h2>
1036
1037<h3 id="different_method_sets">
1038Why do T and *T have different method sets?</h3>
1039
1040<p>
1041From the <a href="http://golang.org/doc/go_spec.html#Types">Go Spec</a>:
1042</p>
1043
1044<blockquote>
1045The method set of any other named type <code>T</code> consists of all methods
1046with receiver type <code>T</code>. The method set of the corresponding pointer
1047type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1048<code>T</code> (that is, it also contains the method set of <code>T</code>).
1049</blockquote>
1050
1051<p>
1052If an interface value contains a pointer <code>*T</code>,
1053a method call can obtain a value by dereferencing the pointer,
1054but if an interface value contains a value <code>T</code>,
1055there is no useful way for a method call to obtain a pointer.
1056</p>
1057
1058<p>
1059If not for this restriction, this code:
1060</p>
1061
1062<pre>
1063var buf bytes.Buffer
1064io.Copy(buf, os.Stdin)
1065</pre>
1066
1067<p>
1068would copy standard input into a <i>copy</i> of <code>buf</code>,
1069not into <code>buf</code> itself.
1070This is almost never the desired behavior.
1071</p>
1072
1073<h3 id="closures_and_goroutines">
Rob Pikefcfed142012-01-23 08:39:53 -08001074What happens with closures running as goroutines?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001075
1076<p>
1077Some confusion may arise when using closures with concurrency.
1078Consider the following program:
1079</p>
1080
1081<pre>
1082func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001083 done := make(chan bool)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001084
Rob Pikefcfed142012-01-23 08:39:53 -08001085 values := []string{ "a", "b", "c" }
1086 for _, v := range values {
1087 go func() {
1088 fmt.Println(v)
1089 done &lt;- true
1090 }()
1091 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001092
Rob Pikefcfed142012-01-23 08:39:53 -08001093 // wait for all goroutines to complete before exiting
1094 for _ = range values {
1095 &lt;-done
1096 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001097}
1098</pre>
1099
1100<p>
1101One might mistakenly expect to see <code>a, b, c</code> as the output.
1102What you'll probably see instead is <code>c, c, c</code>. This is because
Rob Pikefcfed142012-01-23 08:39:53 -08001103each iteration of the loop uses the same instance of the variable <code>v</code>, so
1104each closure shares that single variable. When the closure runs, it prints the
1105value of <code>v</code> at the time <code>fmt.Println</code> is executed,
1106but <code>v</code> may have been modified since the goroutine was launched.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001107</p>
1108
1109<p>
1110To bind the value of <code>v</code> to each closure as they are launched, one
1111could modify the inner loop to read:
1112</p>
1113
1114<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001115 for _, v := range values {
1116 go func(<b>u</b> string) {
1117 fmt.Println(<b>u</b>)
1118 done &lt;- true
1119 }(<b>v</b>)
1120 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001121</pre>
1122
1123<p>
1124In this example, the value of <code>v</code> is passed as an argument to the
1125anonymous function. That value is then accessible inside the function as
1126the variable <code>u</code>.
1127</p>
1128
1129<h2 id="Control_flow">Control flow</h2>
1130
1131<h3 id="Does_Go_have_a_ternary_form">
1132Does Go have the <code>?:</code> operator?</h3>
1133
1134<p>
1135There is no ternary form in Go. You may use the following to achieve the same
1136result:
1137</p>
1138
1139<pre>
1140if expr {
Rob Pikefcfed142012-01-23 08:39:53 -08001141 n = trueVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001142} else {
Rob Pikefcfed142012-01-23 08:39:53 -08001143 n = falseVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001144}
1145</pre>
1146
1147<h2 id="Packages_Testing">Packages and Testing</h2>
1148
1149<h3 id="How_do_I_create_a_multifile_package">
1150How do I create a multifile package?</h3>
1151
1152<p>
1153Put all the source files for the package in a directory by themselves.
1154Source files can refer to items from different files at will; there is
1155no need for forward declarations or a header file.
1156</p>
1157
1158<p>
1159Other than being split into multiple files, the package will compile and test
1160just like a single-file package.
1161</p>
1162
1163<h3 id="How_do_I_write_a_unit_test">
1164How do I write a unit test?</h3>
1165
1166<p>
1167Create a new file ending in <code>_test.go</code> in the same directory
1168as your package sources. Inside that file, <code>import "testing"</code>
1169and write functions of the form
1170</p>
1171
1172<pre>
1173func TestFoo(t *testing.T) {
1174 ...
1175}
1176</pre>
1177
1178<p>
1179Run <code>gotest</code> in that directory.
1180That script finds the <code>Test</code> functions,
1181builds a test binary, and runs it.
1182</p>
1183
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001184<p>See the <a href="/doc/code.html">How to Write Go Code</a> document for more details.</p>
1185
Rob Pikef6615f12011-11-09 13:19:23 -08001186<h3 id="testing_framework">
1187Where is my favorite helper function for testing?</h3>
1188
1189<p>
1190Go's standard <code>testing</code> package makes it easy to write unit tests, but it lacks
1191features provided in other language's testing frameworks such as assertion functions.
1192An <a href="#assertions">earlier section</a> of this document explained why Go
1193doesn't have assertions, and
1194the same arguments apply to the use of <code>assert</code> in tests.
1195Proper error handling means letting other tests run after one has failed, so
1196that the person debugging the failure gets a complete picture of what is
1197wrong. It is more useful for a test to report that
1198<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
11992, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
1200answer for 2 and therefore no more tests were run. The programmer who
1201triggers the test failure may not be familiar with the code that fails.
1202Time invested writing a good error message now pays off later when the
1203test breaks.
1204</p>
1205
1206<p>
1207A related point is that testing frameworks tend to develop into mini-languages
1208of their own, with conditionals and controls and printing mechanisms,
1209but Go already has all those capabilities; why recreate them?
1210We'd rather write tests in Go; it's one fewer language to learn and the
1211approach keeps the tests straightforward and easy to understand.
1212</p>
1213
1214<p>
1215If the amount of extra code required to write
1216good errors seems repetitive and overwhelming, the test might work better if
1217table-driven, iterating over a list of inputs and outputs defined
1218in a data structure (Go has excellent support for data structure literals).
1219The work to write a good test and good error messages will then be amortized over many
1220test cases. The standard Go library is full of illustrative examples, such as in
1221<a href="http://golang.org/src/pkg/fmt/fmt_test.go">the formatting
1222tests for the <code>fmt</code> package</a>.
1223</p>
1224
Russ Cox32274452009-10-22 00:13:51 -07001225
1226<h2 id="Implementation">Implementation</h2>
1227
1228<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1229What compiler technology is used to build the compilers?</h3>
1230
1231<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001232<code>Gccgo</code> has a C++ front-end with a recursive descent parser coupled to the
1233standard GCC back end. <code>Gc</code> is written in C using
1234<code>yacc</code>/<code>bison</code> for the parser.
Russ Cox32274452009-10-22 00:13:51 -07001235Although it's a new program, it fits in the Plan 9 C compiler suite
1236(<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>)
1237and uses a variant of the Plan 9 loader to generate ELF binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001238</p>
Russ Cox32274452009-10-22 00:13:51 -07001239
1240<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001241We considered writing <code>6g</code>, the original Go compiler, in Go itself but
Russ Cox32274452009-10-22 00:13:51 -07001242elected not to do so because of the difficulties of bootstrapping and
Rob Pike0c2a4792009-11-01 20:50:42 -08001243especially of open source distribution&mdash;you'd need a Go compiler to
1244set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
1245consider writing a compiler in Go, which might well happen. (Go would be a
Russ Cox32274452009-10-22 00:13:51 -07001246fine language in which to implement a compiler; a native lexer and
Rob Pike0c2a4792009-11-01 20:50:42 -08001247parser are already available in <a href="/pkg/go/"><code>/pkg/go</code></a>.)
Evan Shaw64d85762011-05-22 14:56:12 +10001248</p>
Russ Cox32274452009-10-22 00:13:51 -07001249
1250<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001251We also considered using LLVM for <code>6g</code> but we felt it was too large and
Russ Cox32274452009-10-22 00:13:51 -07001252slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001253</p>
Russ Cox32274452009-10-22 00:13:51 -07001254
Rob Pike966bf712011-03-01 13:54:22 -08001255<h3 id="How_is_the_run_time_support_implemented">
1256How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001257
1258<p>
Rob Pike966bf712011-03-01 13:54:22 -08001259Again due to bootstrapping issues, the run-time code is mostly in C (with a
Russ Cox32274452009-10-22 00:13:51 -07001260tiny bit of assembler) although Go is capable of implementing most of
Rob Pike966bf712011-03-01 13:54:22 -08001261it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
David Symondsbe96fa52011-07-31 12:59:58 +10001262<code>Gc</code> uses a custom library to keep the footprint under
Rob Pike0c2a4792009-11-01 20:50:42 -08001263control; it is
1264compiled with a version of the Plan 9 C compiler that supports
1265segmented stacks for goroutines.
Rob Pike86494442011-11-08 16:26:03 -08001266The <code>gccgo</code> compiler also implements segmented
1267stacks, supported by recent modifications to its linker.
Evan Shaw64d85762011-05-22 14:56:12 +10001268</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001269
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001270<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1271Why is my trivial program such a large binary?</h3>
1272
1273<p>
Rob Pike86494442011-11-08 16:26:03 -08001274The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>)
1275do static linking. All Go binaries therefore include the Go
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001276run-time, along with the run-time type information necessary to support dynamic
1277type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001278</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001279
1280<p>
1281A trivial C "hello, world" program compiled and linked statically using gcc
Rob Pikece0de422011-03-08 11:47:41 -08001282on Linux is around 750 kB. An equivalent Go program is around 1.1 MB, but
Rob Pike966bf712011-03-01 13:54:22 -08001283that includes more powerful run-time support. We believe that with some effort
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001284the size of Go binaries can be reduced.
Evan Shaw64d85762011-05-22 14:56:12 +10001285</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001286
Rob Pike7d87f3d2011-08-06 11:21:59 +10001287<h3 id="unused_variables_and_imports">
1288Can I stop these complaints about my unused variable/import?</h3>
1289
1290<p>
1291The presence of an unused variable may indicate a bug, while
1292unused imports just slow down compilation.
1293Accumulate enough unused imports in your code tree and
1294things can get very slow.
1295For these reasons, Go allows neither.
1296</p>
1297
1298<p>
1299When developing code, it's common to create these situations
1300temporarily and it can be annoying to have to edit them out before the
1301program will compile.
1302</p>
1303
1304<p>
1305Some have asked for a compiler option to turn those checks off
1306or at least reduce them to warnings.
1307Such an option has not been added, though,
1308because compiler options should not affect the semantics of the
1309language and because the Go compiler does not report warnings, only
1310errors that prevent compilation.
1311</p>
1312
1313<p>
1314There are two reasons for having no warnings. First, if it's worth
1315complaining about, it's worth fixing in the code. (And if it's not
1316worth fixing, it's not worth mentioning.) Second, having the compiler
1317generate warnings encourages the implementation to warn about weak
1318cases that can make compilation noisy, masking real errors that
1319<em>should</em> be fixed.
1320</p>
1321
1322<p>
1323It's easy to address the situation, though. Use the blank identifier
1324to let unused things persist while you're developing.
1325</p>
1326
1327<pre>
1328import "unused"
1329
1330// This declaration marks the import as used by referencing an
1331// item from the package.
1332var _ = unused.Item // TODO: Delete before committing!
1333
1334func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001335 debugData := debug.Profile()
1336 _ = debugData // Used only during debugging.
1337 ....
Rob Pike7d87f3d2011-08-06 11:21:59 +10001338}
1339</pre>
1340
Andrew Gerrand08575732010-04-21 14:00:56 +10001341<h2 id="Performance">Performance</h2>
1342
1343<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1344Why does Go perform badly on benchmark X?</h3>
1345
1346<p>
1347One of Go's design goals is to approach the performance of C for comparable
1348programs, yet on some benchmarks it does quite poorly, including several
1349in <a href="/test/bench/">test/bench</a>. The slowest depend on libraries
1350for which versions of comparable performance are not available in Go.
Rob Pikefcfed142012-01-23 08:39:53 -08001351For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a>
1352depends on a multi-precision math package, and the C
Andrew Gerrand08575732010-04-21 14:00:56 +10001353versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
1354written in optimized assembler).
Rob Pikefcfed142012-01-23 08:39:53 -08001355Benchmarks that depend on regular expressions
1356(<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are
Rob Pike86494442011-11-08 16:26:03 -08001357essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
Andrew Gerrand08575732010-04-21 14:00:56 +10001358mature, highly optimized regular expression libraries like PCRE.
1359</p>
1360
1361<p>
1362Benchmark games are won by extensive tuning and the Go versions of most
1363of the benchmarks need attention. If you measure comparable C
Rob Pikefcfed142012-01-23 08:39:53 -08001364and Go programs
1365(<a href="/test/bench/shootout/reverse-complement.go">reverse-complement.go</a> is one example), you'll see the two
Andrew Gerrand08575732010-04-21 14:00:56 +10001366languages are much closer in raw performance than this suite would
1367indicate.
1368</p>
1369
1370<p>
1371Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001372better, many libraries need major performance work, and the garbage collector
Rob Pikefcfed142012-01-23 08:39:53 -08001373isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
1374garbage can have a huge effect.)
Andrew Gerrand08575732010-04-21 14:00:56 +10001375</p>
1376
Rob Pike93c4a242011-08-06 07:41:55 +10001377<p>
1378In any case, Go can often be very competitive. See the blog post about
1379<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1380Go programs</a> for an informative example.
1381
Andrew Gerrand4164d602010-09-29 16:52:22 +10001382<h2 id="change_from_c">Changes from C</h2>
1383
1384<h3 id="different_syntax">
1385Why is the syntax so different from C?</h3>
1386<p>
1387Other than declaration syntax, the differences are not major and stem
1388from two desires. First, the syntax should feel light, without too
1389many mandatory keywords, repetition, or arcana. Second, the language
1390has been designed to be easy to analyze
1391and can be parsed without a symbol table. This makes it much easier
1392to build tools such as debuggers, dependency analyzers, automated
1393documentation extractors, IDE plug-ins, and so on. C and its
1394descendants are notoriously difficult in this regard.
1395</p>
1396
1397<h3 id="declarations_backwards">
1398Why are declarations backwards?</h3>
1399<p>
1400They're only backwards if you're used to C. In C, the notion is that a
1401variable is declared like an expression denoting its type, which is a
1402nice idea, but the type and expression grammars don't mix very well and
1403the results can be confusing; consider function pointers. Go mostly
1404separates expression and type syntax and that simplifies things (using
1405prefix <code>*</code> for pointers is an exception that proves the rule). In C,
1406the declaration
1407</p>
1408<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001409 int* a, b;
Andrew Gerrand4164d602010-09-29 16:52:22 +10001410</pre>
1411<p>
1412declares <code>a</code> to be a pointer but not <code>b</code>; in Go
1413</p>
1414<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001415 var a, b *int
Andrew Gerrand4164d602010-09-29 16:52:22 +10001416</pre>
1417<p>
1418declares both to be pointers. This is clearer and more regular.
1419Also, the <code>:=</code> short declaration form argues that a full variable
1420declaration should present the same order as <code>:=</code> so
1421</p>
1422<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001423 var a uint64 = 1
Andrew Gerrand4164d602010-09-29 16:52:22 +10001424</pre>
1425has the same effect as
1426<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001427 a := uint64(1)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001428</pre>
1429<p>
1430Parsing is also simplified by having a distinct grammar for types that
1431is not just the expression grammar; keywords such as <code>func</code>
1432and <code>chan</code> keep things clear.
1433</p>
1434
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001435<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001436See the article about
1437<a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a>
1438for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001439</p>
1440
Andrew Gerrand4164d602010-09-29 16:52:22 +10001441<h3 id="no_pointer_arithmetic">
1442Why is there no pointer arithmetic?</h3>
1443<p>
1444Safety. Without pointer arithmetic it's possible to create a
1445language that can never derive an illegal address that succeeds
1446incorrectly. Compiler and hardware technology have advanced to the
1447point where a loop using array indices can be as efficient as a loop
1448using pointer arithmetic. Also, the lack of pointer arithmetic can
1449simplify the implementation of the garbage collector.
1450</p>
1451
1452<h3 id="inc_dec">
1453Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
1454<p>
1455Without pointer arithmetic, the convenience value of pre- and postfix
1456increment operators drops. By removing them from the expression
1457hierarchy altogether, expression syntax is simplified and the messy
1458issues around order of evaluation of <code>++</code> and <code>--</code>
1459(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
1460are eliminated as well. The simplification is
1461significant. As for postfix vs. prefix, either would work fine but
1462the postfix version is more traditional; insistence on prefix arose
1463with the STL, a library for a language whose name contains, ironically, a
1464postfix increment.
1465</p>
1466
1467<h3 id="semicolons">
1468Why are there braces but no semicolons? And why can't I put the opening
1469brace on the next line?</h3>
1470<p>
1471Go uses brace brackets for statement grouping, a syntax familiar to
1472programmers who have worked with any language in the C family.
1473Semicolons, however, are for parsers, not for people, and we wanted to
1474eliminate them as much as possible. To achieve this goal, Go borrows
1475a trick from BCPL: the semicolons that separate statements are in the
1476formal grammar but are injected automatically, without lookahead, by
1477the lexer at the end of any line that could be the end of a statement.
1478This works very well in practice but has the effect that it forces a
1479brace style. For instance, the opening brace of a function cannot
1480appear on a line by itself.
1481</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001482
Andrew Gerrand4164d602010-09-29 16:52:22 +10001483<p>
1484Some have argued that the lexer should do lookahead to permit the
1485brace to live on the next line. We disagree. Since Go code is meant
1486to be formatted automatically by
1487<a href="http://golang.org/cmd/gofmt/"><code>gofmt</code></a>,
1488<i>some</i> style must be chosen. That style may differ from what
1489you've used in C or Java, but Go is a new language and
1490<code>gofmt</code>'s style is as good as any other. More
1491important&mdash;much more important&mdash;the advantages of a single,
1492programmatically mandated format for all Go programs greatly outweigh
1493any perceived disadvantages of the particular style.
1494Note too that Go's style means that an interactive implementation of
1495Go can use the standard syntax one line at a time without special rules.
1496</p>
1497
1498<h3 id="garbage_collection">
1499Why do garbage collection? Won't it be too expensive?</h3>
1500<p>
1501One of the biggest sources of bookkeeping in systems programs is
1502memory management. We feel it's critical to eliminate that
1503programmer overhead, and advances in garbage collection
1504technology in the last few years give us confidence that we can
1505implement it with low enough overhead and no significant
Rob Pikefcfed142012-01-23 08:39:53 -08001506latency.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001507</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001508
Andrew Gerrand4164d602010-09-29 16:52:22 +10001509<p>
1510Another point is that a large part of the difficulty of concurrent
1511and multi-threaded programming is memory management;
1512as objects get passed among threads it becomes cumbersome
1513to guarantee they become freed safely.
1514Automatic garbage collection makes concurrent code far easier to write.
1515Of course, implementing garbage collection in a concurrent environment is
1516itself a challenge, but meeting it once rather than in every
1517program helps everyone.
1518</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001519
Andrew Gerrand4164d602010-09-29 16:52:22 +10001520<p>
1521Finally, concurrency aside, garbage collection makes interfaces
1522simpler because they don't need to specify how memory is managed across them.
1523</p>
Rob Pike93c4a242011-08-06 07:41:55 +10001524
1525<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001526The current implementation is a parallel mark-and-sweep
1527collector but a future version might take a different approach.
1528</p>
1529
1530<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001531On the topic of performance, keep in mind that Go gives the programmer
1532considerable control over memory layout and allocation, much more than
1533is typical in garbage-collected languages. A careful programmer can reduce
1534the garbage collection overhead dramatically by using the language well;
1535see the article about
1536<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1537Go programs</a> for a worked example, including a demonstration of Go's
1538profiling tools.
1539</p>