blob: 8264e1940a80eaf999110bef0fa16ad00929120e [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
Rob Pike8de50802012-07-16 13:31:15 -070057<h3 id="What_is_the_status_of_the_project">
58What is the status of the project?</h3>
59
60<p>
61Go became a public open source project on November 10, 2009.
62After a couple of years of very active design and development, stability was called for and
63Go 1 was <a href="http://blog.golang.org/2012/03/go-version-1-is-released.html">released</a>
64on March 28, 2012.
65Go 1, which includes a <a href="/ref/spec">language specification</a>,
66<a href="/pkg/">standard libraries</a>,
67and <a href="/cmd/go/">custom tools</a>,
68provides a stable foundation for creating reliable products, projects, and publications.
69</p>
70
71<p>
72With that stability established, we are using Go to develop programs, products, and tools rather than
73actively changing the language and libraries.
74In fact, the purpose of Go 1 is to provide <a href="/doc/go1compat.html">long-term stability</a>.
75Backwards-incompatible changes will not be made to any Go 1 point release.
76We want to use what we have to learn how a future version of Go might look, rather than to play with
77the language underfoot.
78</p>
79
80<p>
81Of course, development will continue on Go itself, but the focus will be on performance, reliability,
82portability and the addition of new functionality such as improved support for internationalization.
83</p>
84
85<p>
86There may well be a Go 2 one day, but not for a few years and it will be influenced by what we learn using Go 1 as it is today.
87</p>
88
Russ Cox32274452009-10-22 00:13:51 -070089<h3 id="What_is_the_origin_of_the_name">
90What is the origin of the name?</h3>
91
92<p>
Russ Coxe434f1a2009-11-07 17:31:22 -080093&ldquo;Ogle&rdquo; would be a good name for a Go debugger.
Evan Shaw64d85762011-05-22 14:56:12 +100094</p>
Russ Cox32274452009-10-22 00:13:51 -070095
Rob Pikebdecae92009-11-23 17:34:23 -080096<h3 id="Whats_the_origin_of_the_mascot">
97What's the origin of the mascot?</h3>
98
99<p>
100The mascot and logo were designed by
101<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
102<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
103the Plan 9 bunny.
104The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
105T-shirt design some years ago.
106The logo and mascot are covered by the
107<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
108license.
109</p>
110
Andrew Gerrand4164d602010-09-29 16:52:22 +1000111<h3 id="history">
112What is the history of the project?</h3>
113<p>
114Robert Griesemer, Rob Pike and Ken Thompson started sketching the
115goals for a new language on the white board on September 21, 2007.
116Within a few days the goals had settled into a plan to do something
117and a fair idea of what it would be. Design continued part-time in
118parallel with unrelated work. By January 2008, Ken had started work
119on a compiler with which to explore ideas; it generated C code as its
120output. By mid-year the language had become a full-time project and
121had settled enough to attempt a production compiler. In May 2008,
122Ian Taylor independently started on a GCC front end for Go using the
123draft specification. Russ Cox joined in late 2008 and helped move the language
124and libraries from prototype to reality.
125</p>
126
127<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000128Go became a public open source project on November 10, 2009.
129Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000130</p>
131
Andrew Gerrand4164d602010-09-29 16:52:22 +1000132<h3 id="creating_a_new_language">
133Why are you creating a new language?</h3>
134<p>
135Go was born out of frustration with existing languages and
136environments for systems programming. Programming had become too
137difficult and the choice of languages was partly to blame. One had to
138choose either efficient compilation, efficient execution, or ease of
139programming; all three were not available in the same mainstream
140language. Programmers who could were choosing ease over
141safety and efficiency by moving to dynamically typed languages such as
142Python and JavaScript rather than C++ or, to a lesser extent, Java.
143</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000144
Andrew Gerrand4164d602010-09-29 16:52:22 +1000145<p>
146Go is an attempt to combine the ease of programming of an interpreted,
147dynamically typed
148language with the efficiency and safety of a statically typed, compiled language.
149It also aims to be modern, with support for networked and multicore
150computing. Finally, it is intended to be <i>fast</i>: it should take
151at most a few seconds to build a large executable on a single computer.
152To meet these goals required addressing a number of
153linguistic issues: an expressive but lightweight type system;
154concurrency and garbage collection; rigid dependency specification;
155and so on. These cannot be addressed well by libraries or tools; a new
156language was called for.
157</p>
158
Andrew Gerrand4164d602010-09-29 16:52:22 +1000159<h3 id="ancestors">
160What are Go's ancestors?</h3>
161<p>
162Go is mostly in the C family (basic syntax),
163with significant input from the Pascal/Modula/Oberon
164family (declarations, packages),
165plus some ideas from languages
166inspired by Tony Hoare's CSP,
167such as Newsqueak and Limbo (concurrency).
168However, it is a new language across the board.
169In every respect the language was designed by thinking
170about what programmers do and how to make programming, at least the
171kind of programming we do, more effective, which means more fun.
172</p>
173
Andrew Gerrand4164d602010-09-29 16:52:22 +1000174<h3 id="principles">
175What are the guiding principles in the design?</h3>
176<p>
177Programming today involves too much bookkeeping, repetition, and
178clerical work. As Dick Gabriel says, &ldquo;Old programs read
179like quiet conversations between a well-spoken research worker and a
180well-studied mechanical colleague, not as a debate with a compiler.
181Who'd have guessed sophistication bought such noise?&rdquo;
182The sophistication is worthwhile&mdash;no one wants to go back to
183the old languages&mdash;but can it be more quietly achieved?
184</p>
185<p>
186Go attempts to reduce the amount of typing in both senses of the word.
187Throughout its design, we have tried to reduce clutter and
188complexity. There are no forward declarations and no header files;
189everything is declared exactly once. Initialization is expressive,
190automatic, and easy to use. Syntax is clean and light on keywords.
191Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
192simple type derivation using the <code>:=</code>
193declare-and-initialize construct. And perhaps most radically, there
194is no type hierarchy: types just <i>are</i>, they don't have to
195announce their relationships. These simplifications allow Go to be
196expressive yet comprehensible without sacrificing, well, sophistication.
197</p>
198<p>
199Another important principle is to keep the concepts orthogonal.
200Methods can be implemented for any type; structures represent data while
201interfaces represent abstraction; and so on. Orthogonality makes it
202easier to understand what happens when things combine.
203</p>
204
Russ Cox32274452009-10-22 00:13:51 -0700205<h2 id="Usage">Usage</h2>
206
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000207<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800208
Evan Shaw64d85762011-05-22 14:56:12 +1000209<p>
210Yes. There are now several Go programs deployed in
Rob Pikefcfed142012-01-23 08:39:53 -0800211production inside Google. A public example is the server behind
212<a href="http://golang.org">http://golang.org</a>.
213It's just the <a href="/cmd/godoc"><code>godoc</code></a>
214document server running in a production configuration on
Dave Cheney82cbcb02012-07-11 09:41:08 -0700215<a href="https://developers.google.com/appengine/">Google App Engine</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000216</p>
Rob Pike7685a672009-11-09 20:25:45 -0800217
Russ Cox32274452009-10-22 00:13:51 -0700218<h3 id="Do_Go_programs_link_with_Cpp_programs">
219Do Go programs link with C/C++ programs?</h3>
220
221<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +1100222There are two Go compiler implementations, <code>gc</code>
223(the <code>6g</code> program and friends) and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800224<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700225therefore only be linked with C programs using the same convention.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000226There is such a C compiler but no C++ compiler.
227<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
228GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000229</p>
Russ Cox32274452009-10-22 00:13:51 -0700230
231<p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000232The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
233&ldquo;foreign function interface&rdquo; to allow safe calling of
234C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000235</p>
236
Russ Cox32274452009-10-22 00:13:51 -0700237
Rob Pike0c2a4792009-11-01 20:50:42 -0800238<h3 id="Does_Go_support_Google_protocol_buffers">
239Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700240
241<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700242A separate open source project provides the necessary compiler plugin and library.
243It is available at
244<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
245</p>
Russ Cox32274452009-10-22 00:13:51 -0700246
Evan Shaw64d85762011-05-22 14:56:12 +1000247
Russ Cox6301fb42009-12-03 17:23:33 -0800248<h3 id="Can_I_translate_the_Go_home_page">
249Can I translate the Go home page into another language?</h3>
250
251<p>
252Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000253However, if you choose to add the Google logo or branding to your site
Russ Cox6301fb42009-12-03 17:23:33 -0800254(it does not appear on <a href="http://golang.org/">golang.org</a>),
255you will need to abide by the guidelines at
256<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
257</p>
258
Russ Cox32274452009-10-22 00:13:51 -0700259<h2 id="Design">Design</h2>
260
Andrew Gerrand4164d602010-09-29 16:52:22 +1000261<h3 id="unicode_identifiers">
262What's up with Unicode identifiers?</h3>
263
264<p>
265It was important to us to extend the space of identifiers from the
266confines of ASCII. Go's rule&mdash;identifier characters must be
267letters or digits as defined by Unicode&mdash;is simple to understand
268and to implement but has restrictions. Combining characters are
269excluded by design, for instance.
270Until there
271is an agreed external definition of what an identifier might be,
272plus a definition of canonicalization of identifiers that guarantees
273no ambiguity, it seemed better to keep combining characters out of
274the mix. Thus we have a simple rule that can be expanded later
275without breaking programs, one that avoids bugs that would surely arise
276from a rule that admits ambiguous identifiers.
277</p>
278
279<p>
280On a related note, since an exported identifier must begin with an
281upper-case letter, identifiers created from &ldquo;letters&rdquo;
282in some languages can, by definition, not be exported. For now the
283only solution is to use something like <code>X日本語</code>, which
284is clearly unsatisfactory; we are considering other options. The
285case-for-visibility rule is unlikely to change however; it's one
286of our favorite features of Go.
287</p>
288
289<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700290
291<p>
292Every language contains novel features and omits someone's favorite
293feature. Go was designed with an eye on felicity of programming, speed of
294compilation, orthogonality of concepts, and the need to support features
295such as concurrency and garbage collection. Your favorite feature may be
296missing because it doesn't fit, because it affects compilation speed or
297clarity of design, or because it would make the fundamental system model
298too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000299</p>
Russ Cox32274452009-10-22 00:13:51 -0700300
301<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800302If it bothers you that Go is missing feature <var>X</var>,
303please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700304they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000305</p>
Russ Cox32274452009-10-22 00:13:51 -0700306
Andrew Gerrand4164d602010-09-29 16:52:22 +1000307<h3 id="generics">
308Why does Go not have generic types?</h3>
309<p>
310Generics may well be added at some point. We don't feel an urgency for
311them, although we understand some programmers do.
312</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000313
Andrew Gerrand4164d602010-09-29 16:52:22 +1000314<p>
315Generics are convenient but they come at a cost in
316complexity in the type system and run-time. We haven't yet found a
317design that gives value proportionate to the complexity, although we
318continue to think about it. Meanwhile, Go's built-in maps and slices,
319plus the ability to use the empty interface to construct containers
320(with explicit unboxing) mean in many cases it is possible to write
321code that does what generics would enable, if less smoothly.
322</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000323
Andrew Gerrand4164d602010-09-29 16:52:22 +1000324<p>
325This remains an open issue.
326</p>
327
328<h3 id="exceptions">
329Why does Go not have exceptions?</h3>
330<p>
331We believe that coupling exceptions to a control
332structure, as in the <code>try-catch-finally</code> idiom, results in
333convoluted code. It also tends to encourage programmers to label
334too many ordinary errors, such as failing to open a file, as
335exceptional.
336</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000337
Andrew Gerrand4164d602010-09-29 16:52:22 +1000338<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000339Go takes a different approach. For plain error handling, Go's multi-value
340returns make it easy to report an error without overloading the return value.
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100341<a href="/doc/articles/error_handling.html">A canonical error type, coupled
342with Go's other features</a>, makes error handling pleasant but quite different
343from that in other languages.
Rob Pike93c4a242011-08-06 07:41:55 +1000344</p>
345
346<p>
347Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000348of built-in functions to signal and recover from truly exceptional
349conditions. The recovery mechanism is executed only as part of a
350function's state being torn down after an error, which is sufficient
351to handle catastrophe but requires no extra control structures and,
352when used well, can result in clean error-handling code.
353</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000354
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000355<p>
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100356See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000357</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000358
Andrew Gerrand4164d602010-09-29 16:52:22 +1000359<h3 id="assertions">
360Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700361
362<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000363Go doesn't provide assertions. They are undeniably convenient, but our
364experience has been that programmers use them as a crutch to avoid thinking
365about proper error handling and reporting. Proper error handling means that
366servers continue operation after non-fatal errors instead of crashing.
367Proper error reporting means that errors are direct and to the point,
368saving the programmer from interpreting a large crash trace. Precise
369errors are particularly important when the programmer seeing the errors is
370not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000371</p>
Russ Cox32274452009-10-22 00:13:51 -0700372
Andrew Gerrand4164d602010-09-29 16:52:22 +1000373<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000374We 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
Rob Pikefcfed142012-01-23 08:39:53 -0800383for difficulty. We believe this is due partly to complex
Andrew Gerrand4164d602010-09-29 16:52:22 +1000384designs 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:
Rob Pikefcfed142012-01-23 08:39:53 -0800454they can be defined for any sort of data, even built-in types such
455as plain, &ldquo;unboxed&rdquo; integers.
456They are not restricted to structs (classes).
Evan Shaw64d85762011-05-22 14:56:12 +1000457</p>
Russ Cox32274452009-10-22 00:13:51 -0700458
459<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800460Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800461lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000462</p>
Russ Cox32274452009-10-22 00:13:51 -0700463
464<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
465How do I get dynamic dispatch of methods?</h3>
466
467<p>
468The only way to have dynamically dispatched methods is through an
Rob Pikefcfed142012-01-23 08:39:53 -0800469interface. Methods on a struct or any other concrete type are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000470</p>
Russ Cox32274452009-10-22 00:13:51 -0700471
Andrew Gerrand4164d602010-09-29 16:52:22 +1000472<h3 id="inheritance">
473Why is there no type inheritance?</h3>
474<p>
475Object-oriented programming, at least in the best-known languages,
476involves too much discussion of the relationships between types,
477relationships that often could be derived automatically. Go takes a
478different approach.
479</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000480
Andrew Gerrand4164d602010-09-29 16:52:22 +1000481<p>
482Rather than requiring the programmer to declare ahead of time that two
483types are related, in Go a type automatically satisfies any interface
484that specifies a subset of its methods. Besides reducing the
485bookkeeping, this approach has real advantages. Types can satisfy
486many interfaces at once, without the complexities of traditional
487multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000488Interfaces can be very lightweight&mdash;an interface with
489one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000490Interfaces can be added after the fact if a new idea comes along
491or for testing&mdash;without annotating the original types.
492Because there are no explicit relationships between types
493and interfaces, there is no type hierarchy to manage or discuss.
494</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000495
Andrew Gerrand4164d602010-09-29 16:52:22 +1000496<p>
497It's possible to use these ideas to construct something analogous to
498type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
499enables formatted printing to any output, not just a file, or how the
500<code>bufio</code> package can be completely separate from file I/O,
Rob Pike86494442011-11-08 16:26:03 -0800501or how the <code>image</code> packages generate compressed
502image files. All these ideas stem from a single interface
Andrew Gerrand4164d602010-09-29 16:52:22 +1000503(<code>io.Writer</code>) representing a single method
504(<code>Write</code>). And that's only scratching the surface.
Rob Pike5cff1902012-02-20 12:42:50 +1100505Go's interfaces have a profound influence on how programs are structured.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000506</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000507
Andrew Gerrand4164d602010-09-29 16:52:22 +1000508<p>
509It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000510dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000511</p>
512
513<h3 id="methods_on_basics">
514Why is <code>len</code> a function and not a method?</h3>
515<p>
516We debated this issue but decided
517implementing <code>len</code> and friends as functions was fine in practice and
518didn't complicate questions about the interface (in the Go type sense)
519of basic types.
520</p>
521
522<h3 id="overloading">
523Why does Go not support overloading of methods and operators?</h3>
524<p>
525Method dispatch is simplified if it doesn't need to do type matching as well.
526Experience with other languages told us that having a variety of
527methods with the same name but different signatures was occasionally useful
528but that it could also be confusing and fragile in practice. Matching only by name
529and requiring consistency in the types was a major simplifying decision
530in Go's type system.
531</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000532
Andrew Gerrand4164d602010-09-29 16:52:22 +1000533<p>
534Regarding operator overloading, it seems more a convenience than an absolute
535requirement. Again, things are simpler without it.
536</p>
537
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100538<h3 id="implements_interface">
539Why doesn't Go have "implements" declarations?</h3>
540
541<p>
542A Go type satisfies an interface by implementing the methods of that interface,
543nothing more. This property allows interfaces to be defined and used without
544having to modify existing code. It enables a kind of "duck typing" that
545promotes separation of concerns and improves code re-use, and makes it easier
546to build on patterns that emerge as the code develops.
547The semantics of interfaces is one of the main reasons for Go's nimble,
548lightweight feel.
549</p>
550
551<p>
552See the <a href="#inheritance">question on type inheritance</a> for more detail.
553</p>
554
555<h3 id="guarantee_satisfies_interface">
556How can I guarantee my type satisfies an interface?</h3>
557
558<p>
559You can ask the compiler to check that the type <code>T</code> implements the
560interface <code>I</code> by attempting an assignment:
561</p>
562
563<pre>
564type T struct{}
Rob Pikefcfed142012-01-23 08:39:53 -0800565var _ I = T{} // Verify that T implements I.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100566</pre>
567
568<p>
569If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
570at compile time.
571</p>
572
573<p>
574If you wish the users of an interface to explicitly declare that they implement
575it, you can add a method with a descriptive name to the interface's method set.
576For example:
577</p>
578
579<pre>
580type Fooer interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800581 Foo()
582 ImplementsFooer()
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100583}
584</pre>
585
586<p>
587A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100588<code>Fooer</code>, clearly documenting the fact and announcing it in
589<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100590</p>
591
592<pre>
593type Bar struct{}
594func (b Bar) ImplementsFooer() {}
595func (b Bar) Foo() {}
596</pre>
597
598<p>
599Most code doesn't make use of such constraints, since they limit the utility of
600the interface idea. Sometimes, though, they're necessary to resolve ambiguities
601among similar interfaces.
602</p>
603
Rob Pike93c4a242011-08-06 07:41:55 +1000604<h3 id="t_and_equal_interface">
605Why doesn't type T satisfy the Equal interface?</h3>
606
607<p>
608Consider this simple interface to represent an object that can compare
609itself with another value:
610</p>
611
612<pre>
613type Equaler interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800614 Equal(Equaler) bool
Rob Pike93c4a242011-08-06 07:41:55 +1000615}
616</pre>
617
618<p>
619and this type, <code>T</code>:
620</p>
621
622<pre>
623type T int
624func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
625</pre>
626
627<p>
628Unlike the analogous situation in some polymorphic type systems,
629<code>T</code> does not implement <code>Equaler</code>.
630The argument type of <code>T.Equal</code> is <code>T</code>,
631not literally the required type <code>Equaler</code>.
632</p>
633
634<p>
635In Go, the type system does not promote the argument of
636<code>Equal</code>; that is the programmer's responsibility, as
637illustrated by the type <code>T2</code>, which does implement
638<code>Equaler</code>:
639</p>
640
641<pre>
642type T2 int
643func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
644</pre>
645
646<p>
647Even this isn't like other type systems, though, because in Go <em>any</em>
648type that satisfies <code>Equaler</code> could be passed as the
649argument to <code>T2.Equal</code>, and at run time we must
650check that the argument is of type <code>T2</code>.
651Some languages arrange to make that guarantee at compile time.
652</p>
653
654<p>
655A related example goes the other way:
656</p>
657
658<pre>
659type Opener interface {
660 Open(name) Reader
661}
662
663func (t T3) Open() *os.File
664</pre>
665
666<p>
667In Go, <code>T3</code> does not satisfy <code>Opener</code>,
668although it might in another language.
669</p>
670
671<p>
672While it is true that Go's type system does less for the programmer
673in such cases, the lack of subtyping makes the rules about
674interface satisfaction very easy to state: are the function's names
675and signatures exactly those of the interface?
676Go's rule is also easy to implement efficiently.
677We feel these benefits offset the lack of
678automatic type promotion. Should Go one day adopt some form of generic
679typing, we expect there would be a way to express the idea of these
680examples and also have them be statically checked.
681</p>
682
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000683<h3 id="convert_slice_of_interface">
684Can I convert a []T to an []interface{}?</h3>
685
686<p>
Rob Pike86494442011-11-08 16:26:03 -0800687Not directly, because they do not have the same representation in memory.
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000688It is necessary to copy the elements individually to the destination
689slice. This example converts a slice of <code>int</code> to a slice of
690<code>interface{}</code>:
691</p>
692
693<pre>
694t := []int{1, 2, 3, 4}
695s := make([]interface{}, len(t))
696for i, v := range t {
Rob Pikefcfed142012-01-23 08:39:53 -0800697 s[i] = v
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000698}
699</pre>
700
Rob Pike1e0f97a2012-02-17 16:27:17 +1100701<h3 id="nil_error">
702Why is my nil error value not equal to nil?
703</h3>
704
705<p>
706Under the covers, interfaces are implemented as two elements, a type and a value.
707The value, called the interface's dynamic value,
708is an arbitrary concrete value and the type is that of the value.
709For the <code>int</code> value 3, an interface value contains,
710schematically, (<code>int</code>, <code>3</code>).
711</p>
712
713<p>
714An interface value is <code>nil</code> only if the inner value and type are both unset,
715(<code>nil</code>, <code>nil</code>).
716In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
717If we store a pointer of type <code>*int</code> inside
718an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
719(<code>*int</code>, <code>nil</code>).
720Such an interface value will therefore be non-<code>nil</code>
721<em>even when the pointer inside is</em> <code>nil</code>.
722</p>
723
724<p>
725This situation can be confusing, and often arises when a <code>nil</code> value is
726stored inside an interface value such as an <code>error</code> return:
727</p>
728
729<pre>
730func returnsError() error {
731 var p *MyError = nil
732 if bad() {
733 p = ErrBad
734 }
735 return p // Will always return a non-nil error.
736}
737</pre>
738
739<p>
740If all goes well, the function returns a <code>nil</code> <code>p</code>,
741so the return value is an <code>error</code> interface
742value holding (<code>*MyError</code>, <code>nil</code>).
743This means that if the caller compares the returned error to <code>nil</code>,
744it will always look as if there was an error even if nothing bad happened.
745To return a proper <code>nil</code> <code>error</code> to the caller,
746the function must return an explicit <code>nil</code>:
747</p>
748
749
750<pre>
751func returnsError() error {
752 if bad() {
753 return ErrBad
754 }
755 return nil
756}
757</pre>
758
759<p>
760It's a good idea for functions
761that return errors always to use the <code>error</code> type in
762their signature (as we did above) rather than a concrete type such
763as <code>*MyError</code>, to help guarantee the error is
764created correctly. As an example,
765<a href="/pkg/os/#Open"><code>os.Open</code></a>
766returns an <code>error</code> even though, if not <code>nil</code>,
767it's always of concrete type
768<a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
769</p>
770
771<p>
772Similar situations to those described here can arise whenever interfaces are used.
773Just keep in mind that if any concrete value
774has been stored in the interface, the interface will not be <code>nil</code>.
775For more information, see
Shenghou Macb6c09a2012-03-01 14:54:35 +0800776<a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
Rob Pike1e0f97a2012-02-17 16:27:17 +1100777</p>
778
779
Rob Pike7d87f3d2011-08-06 11:21:59 +1000780<h3 id="unions">
781Why are there no untagged unions, as in C?</h3>
782
783<p>
784Untagged unions would violate Go's memory safety
785guarantees.
786</p>
787
788<h3 id="variant_types">
789Why does Go not have variant types?</h3>
790
791<p>
792Variant types, also known as algebraic types, provide a way to specify
793that a value might take one of a set of other types, but only those
794types. A common example in systems programming would specify that an
795error is, say, a network error, a security error or an application
796error and allow the caller to discriminate the source of the problem
797by examining the type of the error. Another example is a syntax tree
798in which each node can be a different type: declaration, statement,
799assignment and so on.
800</p>
801
802<p>
803We considered adding variant types to Go, but after discussion
804decided to leave them out because they overlap in confusing ways
805with interfaces. What would happen if the elements of a variant type
806were themselves interfaces?
807</p>
808
809<p>
810Also, some of what variant types address is already covered by the
811language. The error example is easy to express using an interface
812value to hold the error and a type switch to discriminate cases. The
813syntax tree example is also doable, although not as elegantly.
814</p>
815
Andrew Gerrand4164d602010-09-29 16:52:22 +1000816<h2 id="values">Values</h2>
817
818<h3 id="conversions">
819Why does Go not provide implicit numeric conversions?</h3>
820<p>
821The convenience of automatic conversion between numeric types in C is
822outweighed by the confusion it causes. When is an expression unsigned?
823How big is the value? Does it overflow? Is the result portable, independent
824of the machine on which it executes?
825It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
826are not easy to implement and inconsistent across architectures.
827For reasons of portability, we decided to make things clear and straightforward
828at the cost of some explicit conversions in the code.
829The definition of constants in Go&mdash;arbitrary precision values free
830of signedness and size annotations&mdash;ameliorates matters considerably,
831though.
832</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000833
Andrew Gerrand4164d602010-09-29 16:52:22 +1000834<p>
835A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
836are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
837type is generic; if you care about how many bits an integer holds, Go
838encourages you to be explicit.
839</p>
840
841<h3 id="builtin_maps">
842Why are maps built in?</h3>
843<p>
844The same reason strings are: they are such a powerful and important data
845structure that providing one excellent implementation with syntactic support
846makes programming more pleasant. We believe that Go's implementation of maps
847is strong enough that it will serve for the vast majority of uses.
848If a specific application can benefit from a custom implementation, it's possible
849to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
850</p>
851
Andrew Gerrand4164d602010-09-29 16:52:22 +1000852<h3 id="map_keys">
Rob Pikefcfed142012-01-23 08:39:53 -0800853Why don't maps allow slices as keys?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000854<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800855Map lookup requires an equality operator, which slices do not implement.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000856They don't implement equality because equality is not well defined on such types;
857there are multiple considerations involving shallow vs. deep comparison, pointer vs.
Rob Pikefcfed142012-01-23 08:39:53 -0800858value comparison, how to deal with recursive types, and so on.
859We may revisit this issue&mdash;and implementing equality for slices
Andrew Gerrand4164d602010-09-29 16:52:22 +1000860will not invalidate any existing programs&mdash;but without a clear idea of what
Rob Pike5cff1902012-02-20 12:42:50 +1100861equality of slices should mean, it was simpler to leave it out for now.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000862</p>
863
Rob Pikefcfed142012-01-23 08:39:53 -0800864<p>
Rob Pike5cff1902012-02-20 12:42:50 +1100865In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
866types can be used as map keys. Slices still do not have a definition of equality, though.
Rob Pikefcfed142012-01-23 08:39:53 -0800867</p>
868
Andrew Gerrand4164d602010-09-29 16:52:22 +1000869<h3 id="references">
870Why are maps, slices, and channels references while arrays are values?</h3>
871<p>
872There's a lot of history on that topic. Early on, maps and channels
873were syntactically pointers and it was impossible to declare or use a
874non-pointer instance. Also, we struggled with how arrays should work.
875Eventually we decided that the strict separation of pointers and
876values made the language harder to use. Introducing reference types,
877including slices to handle the reference form of arrays, resolved
878these issues. Reference types add some regrettable complexity to the
879language but they have a large effect on usability: Go became a more
880productive, comfortable language when they were introduced.
881</p>
882
Russ Cox32274452009-10-22 00:13:51 -0700883<h2 id="Writing_Code">Writing Code</h2>
884
885<h3 id="How_are_libraries_documented">
886How are libraries documented?</h3>
887
888<p>
889There is a program, <code>godoc</code>, written in Go, that extracts
890package documentation from the source code. It can be used on the
891command line or on the web. An instance is running at
Rob Pike0c2a4792009-11-01 20:50:42 -0800892<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -0800893In fact, <code>godoc</code> implements the full site at
Rob Pike0c2a4792009-11-01 20:50:42 -0800894<a href="http://golang.org/">http://golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000895</p>
Russ Cox32274452009-10-22 00:13:51 -0700896
897<h3 id="Is_there_a_Go_programming_style_guide">
898Is there a Go programming style guide?</h3>
899
900<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800901Eventually, there may be a small number of rules to guide things
902like naming, layout, and file organization.
903The document <a href="effective_go.html">Effective Go</a>
904contains some style advice.
905More directly, the program <code>gofmt</code> is a pretty-printer
906whose purpose is to enforce layout rules; it replaces the usual
907compendium of do's and don'ts that allows interpretation.
908All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +1000909</p>
Russ Cox32274452009-10-22 00:13:51 -0700910
911<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
912How do I submit patches to the Go libraries?</h3>
913
Rob Pike0c2a4792009-11-01 20:50:42 -0800914<p>
915The library sources are in <code>go/src/pkg</code>.
916If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +1000917</p>
Russ Cox32274452009-10-22 00:13:51 -0700918
Rob Pike0c2a4792009-11-01 20:50:42 -0800919<p>
920See the document
921<a href="contribute.html">Contributing to the Go project</a>
922for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +1000923</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000924
925<h2 id="Pointers">Pointers and Allocation</h2>
926
927<h3 id="pass_by_value">
928When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700929
930<p>
Rob Pike86494442011-11-08 16:26:03 -0800931As in all languages in the C family, everything in Go is passed by value.
932That is, a function always gets a copy of the
Andrew Gerrand4164d602010-09-29 16:52:22 +1000933thing being passed, as if there were an assignment statement assigning the
Rob Pike86494442011-11-08 16:26:03 -0800934value to the parameter. For instance, passing an <code>int</code> value
935to a function makes a copy of the <code>int</code>, and passing a pointer
936value makes a copy of the pointer, but not the data it points to.
937(See the next section for a discussion of how this affects method receivers.)
Andrew Gerrand4164d602010-09-29 16:52:22 +1000938</p>
Russ Cox32274452009-10-22 00:13:51 -0700939
940<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800941Map and slice values behave like pointers: they are descriptors that
Andrew Gerrand4164d602010-09-29 16:52:22 +1000942contain pointers to the underlying map or slice data. Copying a map or
943slice value doesn't copy the data it points to. Copying an interface value
944makes a copy of the thing stored in the interface value. If the interface
945value holds a struct, copying the interface value makes a copy of the
946struct. If the interface value holds a pointer, copying the interface value
947makes a copy of the pointer, but again not the data it points to.
948</p>
949
950<h3 id="methods_on_values_or_pointers">
951Should I define methods on values or pointers?</h3>
952
953<pre>
Rob Pike93c4a242011-08-06 07:41:55 +1000954func (s *MyStruct) pointerMethod() { } // method on pointer
955func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +1000956</pre>
Russ Cox32274452009-10-22 00:13:51 -0700957
958<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000959For programmers unaccustomed to pointers, the distinction between these
960two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000961When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike5cff1902012-02-20 12:42:50 +1100962examples) behaves exactly as if it were an argument to the method.
Rob Pike93c4a242011-08-06 07:41:55 +1000963Whether to define the receiver as a value or as a pointer is the same
964question, then, as whether a function argument should be a value or
965a pointer.
966There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000967</p>
968
Rob Pike93c4a242011-08-06 07:41:55 +1000969<p>
970First, and most important, does the method need to modify the
971receiver?
972If it does, the receiver <em>must</em> be a pointer.
973(Slices and maps are reference types, so their story is a little
974more subtle, but for instance to change the length of a slice
975in a method the receiver must still be a pointer.)
976In the examples above, if <code>pointerMethod</code> modifies
977the fields of <code>s</code>,
978the caller will see those changes, but <code>valueMethod</code>
979is called with a copy of the caller's argument (that's the definition
980of passing a value), so changes it makes will be invisible to the caller.
981</p>
982
983<p>
984By the way, pointer receivers are identical to the situation in Java,
985although in Java the pointers are hidden under the covers; it's Go's
986value receivers that are unusual.
987</p>
988
989<p>
990Second is the consideration of efficiency. If the receiver is large,
991a big <code>struct</code> for instance, it will be much cheaper to
992use a pointer receiver.
993</p>
994
995<p>
996Next is consistency. If some of the methods of the type must have
997pointer receivers, the rest should too, so the method set is
998consistent regardless of how the type is used.
999See the section on <a href="#different_method_sets">method sets</a>
1000for details.
1001</p>
1002
1003<p>
1004For types such as basic types, slices, and small <code>structs</code>,
1005a value receiver is very cheap so unless the semantics of the method
1006requires a pointer, a value receiver is efficient and clear.
1007</p>
1008
1009
Andrew Gerrand4164d602010-09-29 16:52:22 +10001010<h3 id="new_and_make">
1011What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001012
1013<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001014In short: <code>new</code> allocates memory, <code>make</code> initializes
1015the slice, map, and channel types.
1016</p>
1017
1018<p>
1019See the <a href="/doc/effective_go.html#allocation_new">relevant section
1020of Effective Go</a> for more details.
1021</p>
1022
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +11001023<h3 id="q_int_sizes">
Andrew Gerrand4164d602010-09-29 16:52:22 +10001024Why is <code>int</code> 32 bits on 64 bit machines?</h3>
1025
1026<p>
Rob Pike80e25fc2011-01-19 23:07:38 -05001027The sizes of <code>int</code> and <code>uint</code> are implementation-specific
1028but the same as each other on a given platform.
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001029The 64 bit Go compilers (both gc and gccgo) use a 32 bit representation for
Rob Pike80e25fc2011-01-19 23:07:38 -05001030<code>int</code>. Code that relies on a particular
1031size of value should use an explicitly sized type, like <code>int64</code>.
1032On the other hand, floating-point scalars and complex
1033numbers are always sized: <code>float32</code>, <code>complex64</code>,
1034etc., because programmers should be aware of precision when using
1035floating-point numbers.
1036The default size of a floating-point constant is <code>float64</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001037</p>
1038
Rob Pike86494442011-11-08 16:26:03 -08001039<p>
1040At the moment, all implementations use 32-bit ints, an essentially arbitrary decision.
1041However, we expect that <code>int</code> will be increased to 64 bits on 64-bit
1042architectures in a future release of Go.
1043</p>
1044
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001045<h3 id="stack_or_heap">
1046How do I know whether a variable is allocated on the heap or the stack?</h3>
1047
1048<p>
1049From a correctness standpoint, you don't need to know.
1050Each variable in Go exists as long as there are references to it.
1051The storage location chosen by the implementation is irrelevant to the
1052semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +10001053</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001054
1055<p>
1056The storage location does have an effect on writing efficient programs.
1057When possible, the Go compilers will allocate variables that are
1058local to a function in that function's stack frame. However, if the
1059compiler cannot prove that the variable is not referenced after the
1060function returns, then the compiler must allocate the variable on the
1061garbage-collected heap to avoid dangling pointer errors.
Rob Pikefcfed142012-01-23 08:39:53 -08001062Also, if a local variable is very large, it might make more sense
1063to store it on the heap rather than the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001064</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001065
1066<p>
Rob Pike86494442011-11-08 16:26:03 -08001067In the current compilers, if a variable has its address taken, that variable
1068is a candidate for allocation on the heap. However, a basic <em>escape
1069analysis</em> recognizes some cases when such variables will not
1070live past the return from the function and can reside on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001071</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001072
Andrew Gerrand4164d602010-09-29 16:52:22 +10001073<h2 id="Concurrency">Concurrency</h2>
1074
1075<h3 id="What_operations_are_atomic_What_about_mutexes">
1076What operations are atomic? What about mutexes?</h3>
1077
1078<p>
1079We haven't fully defined it all yet, but some details about atomicity are
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001080available in the <a href="/ref/mem">Go Memory Model specification</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001081</p>
1082
1083<p>
1084Regarding mutexes, the <a href="/pkg/sync">sync</a>
1085package implements them, but we hope Go programming style will
1086encourage people to try higher-level techniques. In particular, consider
1087structuring your program so that only one goroutine at a time is ever
1088responsible for a particular piece of data.
1089</p>
1090
1091<p>
1092Do not communicate by sharing memory. Instead, share memory by communicating.
1093</p>
1094
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001095<p>
1096See 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.
1097</p>
1098
Andrew Gerrand4164d602010-09-29 16:52:22 +10001099<h3 id="Why_no_multi_CPU">
1100Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1101
1102<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001103You must set the <code>GOMAXPROCS</code> shell environment variable
1104or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a>
1105of the runtime package to allow the
Rob Pikefcfed142012-01-23 08:39:53 -08001106run-time support to utilize more than one OS thread.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001107</p>
1108
1109<p>
Rob Pike86494442011-11-08 16:26:03 -08001110Programs that perform parallel computation should benefit from an increase in
Rob Pike5cff1902012-02-20 12:42:50 +11001111<code>GOMAXPROCS</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001112</p>
1113
1114<h3 id="Why_GOMAXPROCS">
1115Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
1116slower?</h3>
1117
1118<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001119It depends on the nature of your program.
Rob Pike01afb792012-01-26 14:44:38 -08001120Problems that are intrinsically sequential cannot be sped up by adding
1121more goroutines.
1122Concurrency only becomes parallelism when the problem is
1123intrinsically parallel.
1124</p>
1125
1126<p>
1127In practical terms, programs that spend more time
1128communicating on channels than doing computation
1129will experience performance degradation when using
1130multiple OS threads.
1131This is because sending data between threads involves switching
1132contexts, which has significant cost.
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001133For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
Rob Pike01afb792012-01-26 14:44:38 -08001134from the Go specification has no significant parallelism although it launches many
1135goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than
1136to speed it up.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001137</p>
1138
1139<p>
Rob Pike966bf712011-03-01 13:54:22 -08001140Go's goroutine scheduler is not as good as it needs to be. In future, it
1141should recognize such cases and optimize its use of OS threads. For now,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001142<code>GOMAXPROCS</code> should be set on a per-application basis.
1143</p>
1144
Andrew Gerrand4164d602010-09-29 16:52:22 +10001145<h2 id="Functions_methods">Functions and Methods</h2>
1146
1147<h3 id="different_method_sets">
1148Why do T and *T have different method sets?</h3>
1149
1150<p>
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001151From the <a href="/ref/spec#Types">Go Spec</a>:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001152</p>
1153
1154<blockquote>
1155The method set of any other named type <code>T</code> consists of all methods
1156with receiver type <code>T</code>. The method set of the corresponding pointer
1157type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1158<code>T</code> (that is, it also contains the method set of <code>T</code>).
1159</blockquote>
1160
1161<p>
1162If an interface value contains a pointer <code>*T</code>,
1163a method call can obtain a value by dereferencing the pointer,
1164but if an interface value contains a value <code>T</code>,
1165there is no useful way for a method call to obtain a pointer.
1166</p>
1167
1168<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001169Even in cases where the compiler could take the address of a value
1170to pass to the method, if the method modifies the value the changes
1171will be lost in the caller.
1172As a common example, this code:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001173</p>
1174
1175<pre>
1176var buf bytes.Buffer
1177io.Copy(buf, os.Stdin)
1178</pre>
1179
1180<p>
1181would copy standard input into a <i>copy</i> of <code>buf</code>,
1182not into <code>buf</code> itself.
1183This is almost never the desired behavior.
1184</p>
1185
1186<h3 id="closures_and_goroutines">
Rob Pikefcfed142012-01-23 08:39:53 -08001187What happens with closures running as goroutines?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001188
1189<p>
1190Some confusion may arise when using closures with concurrency.
1191Consider the following program:
1192</p>
1193
1194<pre>
1195func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001196 done := make(chan bool)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001197
Rob Pike5cff1902012-02-20 12:42:50 +11001198 values := []string{"a", "b", "c"}
Rob Pikefcfed142012-01-23 08:39:53 -08001199 for _, v := range values {
1200 go func() {
1201 fmt.Println(v)
1202 done &lt;- true
1203 }()
1204 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001205
Rob Pikefcfed142012-01-23 08:39:53 -08001206 // wait for all goroutines to complete before exiting
1207 for _ = range values {
1208 &lt;-done
1209 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001210}
1211</pre>
1212
1213<p>
1214One might mistakenly expect to see <code>a, b, c</code> as the output.
1215What you'll probably see instead is <code>c, c, c</code>. This is because
Rob Pikefcfed142012-01-23 08:39:53 -08001216each iteration of the loop uses the same instance of the variable <code>v</code>, so
1217each closure shares that single variable. When the closure runs, it prints the
1218value of <code>v</code> at the time <code>fmt.Println</code> is executed,
1219but <code>v</code> may have been modified since the goroutine was launched.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001220</p>
1221
1222<p>
1223To bind the value of <code>v</code> to each closure as they are launched, one
1224could modify the inner loop to read:
1225</p>
1226
1227<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001228 for _, v := range values {
1229 go func(<b>u</b> string) {
1230 fmt.Println(<b>u</b>)
1231 done &lt;- true
1232 }(<b>v</b>)
1233 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001234</pre>
1235
1236<p>
1237In this example, the value of <code>v</code> is passed as an argument to the
1238anonymous function. That value is then accessible inside the function as
1239the variable <code>u</code>.
1240</p>
1241
1242<h2 id="Control_flow">Control flow</h2>
1243
1244<h3 id="Does_Go_have_a_ternary_form">
1245Does Go have the <code>?:</code> operator?</h3>
1246
1247<p>
1248There is no ternary form in Go. You may use the following to achieve the same
1249result:
1250</p>
1251
1252<pre>
1253if expr {
Rob Pikefcfed142012-01-23 08:39:53 -08001254 n = trueVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001255} else {
Rob Pikefcfed142012-01-23 08:39:53 -08001256 n = falseVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001257}
1258</pre>
1259
1260<h2 id="Packages_Testing">Packages and Testing</h2>
1261
1262<h3 id="How_do_I_create_a_multifile_package">
1263How do I create a multifile package?</h3>
1264
1265<p>
1266Put all the source files for the package in a directory by themselves.
1267Source files can refer to items from different files at will; there is
1268no need for forward declarations or a header file.
1269</p>
1270
1271<p>
1272Other than being split into multiple files, the package will compile and test
1273just like a single-file package.
1274</p>
1275
1276<h3 id="How_do_I_write_a_unit_test">
1277How do I write a unit test?</h3>
1278
1279<p>
1280Create a new file ending in <code>_test.go</code> in the same directory
1281as your package sources. Inside that file, <code>import "testing"</code>
1282and write functions of the form
1283</p>
1284
1285<pre>
1286func TestFoo(t *testing.T) {
1287 ...
1288}
1289</pre>
1290
1291<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001292Run <code>go test</code> in that directory.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001293That script finds the <code>Test</code> functions,
1294builds a test binary, and runs it.
1295</p>
1296
Rob Pike5cff1902012-02-20 12:42:50 +11001297<p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
1298the <a href="/pkg/testing/"><code>testing</code></a> package
1299and the <a href="/cmd/go/#Test_packages"><code>go test</code></a> subcommand for more details.
1300</p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001301
Rob Pikef6615f12011-11-09 13:19:23 -08001302<h3 id="testing_framework">
1303Where is my favorite helper function for testing?</h3>
1304
1305<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001306Go's standard <a href="/pkg/testing/"><code>testing</code></a> package makes it easy to write unit tests, but it lacks
Rob Pikef6615f12011-11-09 13:19:23 -08001307features provided in other language's testing frameworks such as assertion functions.
1308An <a href="#assertions">earlier section</a> of this document explained why Go
1309doesn't have assertions, and
1310the same arguments apply to the use of <code>assert</code> in tests.
1311Proper error handling means letting other tests run after one has failed, so
1312that the person debugging the failure gets a complete picture of what is
1313wrong. It is more useful for a test to report that
1314<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
13152, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
1316answer for 2 and therefore no more tests were run. The programmer who
1317triggers the test failure may not be familiar with the code that fails.
1318Time invested writing a good error message now pays off later when the
1319test breaks.
1320</p>
1321
1322<p>
1323A related point is that testing frameworks tend to develop into mini-languages
1324of their own, with conditionals and controls and printing mechanisms,
1325but Go already has all those capabilities; why recreate them?
1326We'd rather write tests in Go; it's one fewer language to learn and the
1327approach keeps the tests straightforward and easy to understand.
1328</p>
1329
1330<p>
1331If the amount of extra code required to write
1332good errors seems repetitive and overwhelming, the test might work better if
1333table-driven, iterating over a list of inputs and outputs defined
1334in a data structure (Go has excellent support for data structure literals).
1335The work to write a good test and good error messages will then be amortized over many
1336test cases. The standard Go library is full of illustrative examples, such as in
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001337<a href="/src/pkg/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>.
Rob Pikef6615f12011-11-09 13:19:23 -08001338</p>
1339
Russ Cox32274452009-10-22 00:13:51 -07001340
1341<h2 id="Implementation">Implementation</h2>
1342
1343<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1344What compiler technology is used to build the compilers?</h3>
1345
1346<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001347<code>Gccgo</code> has a C++ front-end with a recursive descent parser coupled to the
1348standard GCC back end. <code>Gc</code> is written in C using
1349<code>yacc</code>/<code>bison</code> for the parser.
Russ Cox32274452009-10-22 00:13:51 -07001350Although it's a new program, it fits in the Plan 9 C compiler suite
1351(<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>)
Shenghou Mac3eaef72012-03-17 15:53:40 +08001352and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001353</p>
Russ Cox32274452009-10-22 00:13:51 -07001354
1355<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001356We considered writing <code>gc</code>, the original Go compiler, in Go itself but
Russ Cox32274452009-10-22 00:13:51 -07001357elected not to do so because of the difficulties of bootstrapping and
Rob Pike0c2a4792009-11-01 20:50:42 -08001358especially of open source distribution&mdash;you'd need a Go compiler to
1359set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
1360consider writing a compiler in Go, which might well happen. (Go would be a
Russ Cox32274452009-10-22 00:13:51 -07001361fine language in which to implement a compiler; a native lexer and
Shenghou Mac3eaef72012-03-17 15:53:40 +08001362parser are already available in the <a href="/pkg/go/"><code>go</code></a> package.)
Evan Shaw64d85762011-05-22 14:56:12 +10001363</p>
Russ Cox32274452009-10-22 00:13:51 -07001364
1365<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001366We also considered using LLVM for <code>gc</code> but we felt it was too large and
Russ Cox32274452009-10-22 00:13:51 -07001367slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001368</p>
Russ Cox32274452009-10-22 00:13:51 -07001369
Rob Pike966bf712011-03-01 13:54:22 -08001370<h3 id="How_is_the_run_time_support_implemented">
1371How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001372
1373<p>
Rob Pike966bf712011-03-01 13:54:22 -08001374Again due to bootstrapping issues, the run-time code is mostly in C (with a
Russ Cox32274452009-10-22 00:13:51 -07001375tiny bit of assembler) although Go is capable of implementing most of
Rob Pike966bf712011-03-01 13:54:22 -08001376it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
David Symondsbe96fa52011-07-31 12:59:58 +10001377<code>Gc</code> uses a custom library to keep the footprint under
Rob Pike0c2a4792009-11-01 20:50:42 -08001378control; it is
1379compiled with a version of the Plan 9 C compiler that supports
1380segmented stacks for goroutines.
Ian Lance Taylorebc40072012-02-17 05:59:15 -08001381The <code>gccgo</code> compiler implements segmented
1382stacks on Linux only, supported by recent modifications to the gold linker.
Evan Shaw64d85762011-05-22 14:56:12 +10001383</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001384
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001385<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1386Why is my trivial program such a large binary?</h3>
1387
1388<p>
Rob Pike86494442011-11-08 16:26:03 -08001389The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>)
1390do static linking. All Go binaries therefore include the Go
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001391run-time, along with the run-time type information necessary to support dynamic
1392type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001393</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001394
1395<p>
Rob Pike0130a312012-03-07 15:29:26 +11001396A simple C "hello, world" program compiled and linked statically using gcc
1397on Linux is around 750 kB,
1398including an implementation of <code>printf</code>.
1399An equivalent Go program using <code>fmt.Printf</code>
1400is around 1.2 MB, but
Rob Pike5cff1902012-02-20 12:42:50 +11001401that includes more powerful run-time support.
Evan Shaw64d85762011-05-22 14:56:12 +10001402</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001403
Rob Pike7d87f3d2011-08-06 11:21:59 +10001404<h3 id="unused_variables_and_imports">
1405Can I stop these complaints about my unused variable/import?</h3>
1406
1407<p>
1408The presence of an unused variable may indicate a bug, while
1409unused imports just slow down compilation.
1410Accumulate enough unused imports in your code tree and
1411things can get very slow.
1412For these reasons, Go allows neither.
1413</p>
1414
1415<p>
1416When developing code, it's common to create these situations
1417temporarily and it can be annoying to have to edit them out before the
1418program will compile.
1419</p>
1420
1421<p>
1422Some have asked for a compiler option to turn those checks off
1423or at least reduce them to warnings.
1424Such an option has not been added, though,
1425because compiler options should not affect the semantics of the
1426language and because the Go compiler does not report warnings, only
1427errors that prevent compilation.
1428</p>
1429
1430<p>
1431There are two reasons for having no warnings. First, if it's worth
1432complaining about, it's worth fixing in the code. (And if it's not
1433worth fixing, it's not worth mentioning.) Second, having the compiler
1434generate warnings encourages the implementation to warn about weak
1435cases that can make compilation noisy, masking real errors that
1436<em>should</em> be fixed.
1437</p>
1438
1439<p>
1440It's easy to address the situation, though. Use the blank identifier
1441to let unused things persist while you're developing.
1442</p>
1443
1444<pre>
1445import "unused"
1446
1447// This declaration marks the import as used by referencing an
1448// item from the package.
1449var _ = unused.Item // TODO: Delete before committing!
1450
1451func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001452 debugData := debug.Profile()
1453 _ = debugData // Used only during debugging.
1454 ....
Rob Pike7d87f3d2011-08-06 11:21:59 +10001455}
1456</pre>
1457
Andrew Gerrand08575732010-04-21 14:00:56 +10001458<h2 id="Performance">Performance</h2>
1459
1460<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1461Why does Go perform badly on benchmark X?</h3>
1462
1463<p>
1464One of Go's design goals is to approach the performance of C for comparable
1465programs, yet on some benchmarks it does quite poorly, including several
Rob Pike5cff1902012-02-20 12:42:50 +11001466in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries
Andrew Gerrand08575732010-04-21 14:00:56 +10001467for which versions of comparable performance are not available in Go.
Rob Pikefcfed142012-01-23 08:39:53 -08001468For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a>
1469depends on a multi-precision math package, and the C
Andrew Gerrand08575732010-04-21 14:00:56 +10001470versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
1471written in optimized assembler).
Rob Pikefcfed142012-01-23 08:39:53 -08001472Benchmarks that depend on regular expressions
1473(<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are
Rob Pike86494442011-11-08 16:26:03 -08001474essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
Andrew Gerrand08575732010-04-21 14:00:56 +10001475mature, highly optimized regular expression libraries like PCRE.
1476</p>
1477
1478<p>
1479Benchmark games are won by extensive tuning and the Go versions of most
1480of the benchmarks need attention. If you measure comparable C
Rob Pikefcfed142012-01-23 08:39:53 -08001481and Go programs
1482(<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 +10001483languages are much closer in raw performance than this suite would
1484indicate.
1485</p>
1486
1487<p>
1488Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001489better, many libraries need major performance work, and the garbage collector
Rob Pikefcfed142012-01-23 08:39:53 -08001490isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
1491garbage can have a huge effect.)
Andrew Gerrand08575732010-04-21 14:00:56 +10001492</p>
1493
Rob Pike93c4a242011-08-06 07:41:55 +10001494<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001495In any case, Go can often be very competitive.
1496There has been significant improvement in the performance of many programs
1497as the language and tools have developed.
1498See the blog post about
Rob Pike93c4a242011-08-06 07:41:55 +10001499<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1500Go programs</a> for an informative example.
1501
Andrew Gerrand4164d602010-09-29 16:52:22 +10001502<h2 id="change_from_c">Changes from C</h2>
1503
1504<h3 id="different_syntax">
1505Why is the syntax so different from C?</h3>
1506<p>
1507Other than declaration syntax, the differences are not major and stem
1508from two desires. First, the syntax should feel light, without too
1509many mandatory keywords, repetition, or arcana. Second, the language
1510has been designed to be easy to analyze
1511and can be parsed without a symbol table. This makes it much easier
1512to build tools such as debuggers, dependency analyzers, automated
1513documentation extractors, IDE plug-ins, and so on. C and its
1514descendants are notoriously difficult in this regard.
1515</p>
1516
1517<h3 id="declarations_backwards">
1518Why are declarations backwards?</h3>
1519<p>
1520They're only backwards if you're used to C. In C, the notion is that a
1521variable is declared like an expression denoting its type, which is a
1522nice idea, but the type and expression grammars don't mix very well and
1523the results can be confusing; consider function pointers. Go mostly
1524separates expression and type syntax and that simplifies things (using
1525prefix <code>*</code> for pointers is an exception that proves the rule). In C,
1526the declaration
1527</p>
1528<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001529 int* a, b;
Andrew Gerrand4164d602010-09-29 16:52:22 +10001530</pre>
1531<p>
1532declares <code>a</code> to be a pointer but not <code>b</code>; in Go
1533</p>
1534<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001535 var a, b *int
Andrew Gerrand4164d602010-09-29 16:52:22 +10001536</pre>
1537<p>
1538declares both to be pointers. This is clearer and more regular.
1539Also, the <code>:=</code> short declaration form argues that a full variable
1540declaration should present the same order as <code>:=</code> so
1541</p>
1542<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001543 var a uint64 = 1
Andrew Gerrand4164d602010-09-29 16:52:22 +10001544</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001545<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001546has the same effect as
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001547</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001548<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001549 a := uint64(1)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001550</pre>
1551<p>
1552Parsing is also simplified by having a distinct grammar for types that
1553is not just the expression grammar; keywords such as <code>func</code>
1554and <code>chan</code> keep things clear.
1555</p>
1556
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001557<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001558See the article about
Francisco Souza6033a482012-03-13 14:46:08 +11001559<a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
Rob Pike93c4a242011-08-06 07:41:55 +10001560for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001561</p>
1562
Andrew Gerrand4164d602010-09-29 16:52:22 +10001563<h3 id="no_pointer_arithmetic">
1564Why is there no pointer arithmetic?</h3>
1565<p>
1566Safety. Without pointer arithmetic it's possible to create a
1567language that can never derive an illegal address that succeeds
1568incorrectly. Compiler and hardware technology have advanced to the
1569point where a loop using array indices can be as efficient as a loop
1570using pointer arithmetic. Also, the lack of pointer arithmetic can
1571simplify the implementation of the garbage collector.
1572</p>
1573
1574<h3 id="inc_dec">
1575Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
1576<p>
1577Without pointer arithmetic, the convenience value of pre- and postfix
1578increment operators drops. By removing them from the expression
1579hierarchy altogether, expression syntax is simplified and the messy
1580issues around order of evaluation of <code>++</code> and <code>--</code>
1581(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
1582are eliminated as well. The simplification is
1583significant. As for postfix vs. prefix, either would work fine but
1584the postfix version is more traditional; insistence on prefix arose
1585with the STL, a library for a language whose name contains, ironically, a
1586postfix increment.
1587</p>
1588
1589<h3 id="semicolons">
1590Why are there braces but no semicolons? And why can't I put the opening
1591brace on the next line?</h3>
1592<p>
1593Go uses brace brackets for statement grouping, a syntax familiar to
1594programmers who have worked with any language in the C family.
1595Semicolons, however, are for parsers, not for people, and we wanted to
1596eliminate them as much as possible. To achieve this goal, Go borrows
1597a trick from BCPL: the semicolons that separate statements are in the
1598formal grammar but are injected automatically, without lookahead, by
1599the lexer at the end of any line that could be the end of a statement.
1600This works very well in practice but has the effect that it forces a
1601brace style. For instance, the opening brace of a function cannot
1602appear on a line by itself.
1603</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001604
Andrew Gerrand4164d602010-09-29 16:52:22 +10001605<p>
1606Some have argued that the lexer should do lookahead to permit the
1607brace to live on the next line. We disagree. Since Go code is meant
1608to be formatted automatically by
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001609<a href="/cmd/gofmt/"><code>gofmt</code></a>,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001610<i>some</i> style must be chosen. That style may differ from what
1611you've used in C or Java, but Go is a new language and
1612<code>gofmt</code>'s style is as good as any other. More
1613important&mdash;much more important&mdash;the advantages of a single,
1614programmatically mandated format for all Go programs greatly outweigh
1615any perceived disadvantages of the particular style.
1616Note too that Go's style means that an interactive implementation of
1617Go can use the standard syntax one line at a time without special rules.
1618</p>
1619
1620<h3 id="garbage_collection">
1621Why do garbage collection? Won't it be too expensive?</h3>
1622<p>
1623One of the biggest sources of bookkeeping in systems programs is
1624memory management. We feel it's critical to eliminate that
1625programmer overhead, and advances in garbage collection
1626technology in the last few years give us confidence that we can
1627implement it with low enough overhead and no significant
Rob Pikefcfed142012-01-23 08:39:53 -08001628latency.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001629</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001630
Andrew Gerrand4164d602010-09-29 16:52:22 +10001631<p>
1632Another point is that a large part of the difficulty of concurrent
1633and multi-threaded programming is memory management;
1634as objects get passed among threads it becomes cumbersome
1635to guarantee they become freed safely.
1636Automatic garbage collection makes concurrent code far easier to write.
1637Of course, implementing garbage collection in a concurrent environment is
1638itself a challenge, but meeting it once rather than in every
1639program helps everyone.
1640</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001641
Andrew Gerrand4164d602010-09-29 16:52:22 +10001642<p>
1643Finally, concurrency aside, garbage collection makes interfaces
1644simpler because they don't need to specify how memory is managed across them.
1645</p>
Rob Pike93c4a242011-08-06 07:41:55 +10001646
1647<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001648The current implementation is a parallel mark-and-sweep
1649collector but a future version might take a different approach.
1650</p>
1651
1652<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001653On the topic of performance, keep in mind that Go gives the programmer
1654considerable control over memory layout and allocation, much more than
1655is typical in garbage-collected languages. A careful programmer can reduce
1656the garbage collection overhead dramatically by using the language well;
1657see the article about
1658<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1659Go programs</a> for a worked example, including a demonstration of Go's
1660profiling tools.
1661</p>