blob: 63ad66c51971b481e799426c8f1ea5741dfddcda [file] [log] [blame]
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11001<!--{
Russ Cox10ea6512012-09-24 20:57:01 -04002 "Title": "FAQ",
3 "Path": "/doc/faq"
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11004}-->
Russ Cox32274452009-10-22 00:13:51 -07005
6<h2 id="Origins">Origins</h2>
7
8<h3 id="What_is_the_purpose_of_the_project">
9What is the purpose of the project?</h3>
10
11<p>
12No major systems language has emerged in over a decade, but over that time
13the computing landscape has changed tremendously. There are several trends:
Rob Pike93c4a242011-08-06 07:41:55 +100014</p>
Russ Cox32274452009-10-22 00:13:51 -070015
16<ul>
17<li>
18Computers are enormously quicker but software development is not faster.
19<li>
20Dependency management is a big part of software development today but the
Russ Coxe434f1a2009-11-07 17:31:22 -080021&ldquo;header files&rdquo; of languages in the C tradition are antithetical to clean
Russ Cox32274452009-10-22 00:13:51 -070022dependency analysis&mdash;and fast compilation.
23<li>
24There is a growing rebellion against cumbersome type systems like those of
25Java and C++, pushing people towards dynamically typed languages such as
Rob Pike0c2a4792009-11-01 20:50:42 -080026Python and JavaScript.
Russ Cox32274452009-10-22 00:13:51 -070027<li>
28Some fundamental concepts such as garbage collection and parallel computation
29are not well supported by popular systems languages.
30<li>
31The emergence of multicore computers has generated worry and confusion.
32</ul>
33
34<p>
35We believe it's worth trying again with a new language, a concurrent,
36garbage-collected language with fast compilation. Regarding the points above:
Rob Pike93c4a242011-08-06 07:41:55 +100037</p>
Russ Cox32274452009-10-22 00:13:51 -070038
39<ul>
40<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080041It is possible to compile a large Go program in a few seconds on a single computer.
Russ Cox32274452009-10-22 00:13:51 -070042<li>
43Go provides a model for software construction that makes dependency
44analysis easy and avoids much of the overhead of C-style include files and
45libraries.
46<li>
Rob Pike0c2a4792009-11-01 20:50:42 -080047Go's type system has no hierarchy, so no time is spent defining the
48relationships between types. Also, although Go has static types the language
Russ Cox32274452009-10-22 00:13:51 -070049attempts to make types feel lighter weight than in typical OO languages.
50<li>
51Go is fully garbage-collected and provides fundamental support for
52concurrent execution and communication.
53<li>
54By its design, Go proposes an approach for the construction of system
55software on multicore machines.
56</ul>
57
Rob Pike8de50802012-07-16 13:31:15 -070058<h3 id="What_is_the_status_of_the_project">
59What is the status of the project?</h3>
60
61<p>
62Go became a public open source project on November 10, 2009.
63After a couple of years of very active design and development, stability was called for and
64Go 1 was <a href="http://blog.golang.org/2012/03/go-version-1-is-released.html">released</a>
65on March 28, 2012.
66Go 1, which includes a <a href="/ref/spec">language specification</a>,
67<a href="/pkg/">standard libraries</a>,
68and <a href="/cmd/go/">custom tools</a>,
69provides a stable foundation for creating reliable products, projects, and publications.
70</p>
71
72<p>
73With that stability established, we are using Go to develop programs, products, and tools rather than
74actively changing the language and libraries.
75In fact, the purpose of Go 1 is to provide <a href="/doc/go1compat.html">long-term stability</a>.
76Backwards-incompatible changes will not be made to any Go 1 point release.
77We want to use what we have to learn how a future version of Go might look, rather than to play with
78the language underfoot.
79</p>
80
81<p>
82Of course, development will continue on Go itself, but the focus will be on performance, reliability,
83portability and the addition of new functionality such as improved support for internationalization.
84</p>
85
86<p>
87There 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.
88</p>
89
Russ Cox32274452009-10-22 00:13:51 -070090<h3 id="What_is_the_origin_of_the_name">
91What is the origin of the name?</h3>
92
93<p>
Russ Coxe434f1a2009-11-07 17:31:22 -080094&ldquo;Ogle&rdquo; would be a good name for a Go debugger.
Evan Shaw64d85762011-05-22 14:56:12 +100095</p>
Russ Cox32274452009-10-22 00:13:51 -070096
Rob Pikebdecae92009-11-23 17:34:23 -080097<h3 id="Whats_the_origin_of_the_mascot">
98What's the origin of the mascot?</h3>
99
100<p>
101The mascot and logo were designed by
102<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
103<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
104the Plan 9 bunny.
105The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
106T-shirt design some years ago.
107The logo and mascot are covered by the
108<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
109license.
110</p>
111
Andrew Gerrand4164d602010-09-29 16:52:22 +1000112<h3 id="history">
113What is the history of the project?</h3>
114<p>
115Robert Griesemer, Rob Pike and Ken Thompson started sketching the
116goals for a new language on the white board on September 21, 2007.
117Within a few days the goals had settled into a plan to do something
118and a fair idea of what it would be. Design continued part-time in
119parallel with unrelated work. By January 2008, Ken had started work
120on a compiler with which to explore ideas; it generated C code as its
121output. By mid-year the language had become a full-time project and
122had settled enough to attempt a production compiler. In May 2008,
123Ian Taylor independently started on a GCC front end for Go using the
124draft specification. Russ Cox joined in late 2008 and helped move the language
125and libraries from prototype to reality.
126</p>
127
128<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000129Go became a public open source project on November 10, 2009.
130Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000131</p>
132
Andrew Gerrand4164d602010-09-29 16:52:22 +1000133<h3 id="creating_a_new_language">
134Why are you creating a new language?</h3>
135<p>
136Go was born out of frustration with existing languages and
137environments for systems programming. Programming had become too
138difficult and the choice of languages was partly to blame. One had to
139choose either efficient compilation, efficient execution, or ease of
140programming; all three were not available in the same mainstream
141language. Programmers who could were choosing ease over
142safety and efficiency by moving to dynamically typed languages such as
143Python and JavaScript rather than C++ or, to a lesser extent, Java.
144</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000145
Andrew Gerrand4164d602010-09-29 16:52:22 +1000146<p>
147Go is an attempt to combine the ease of programming of an interpreted,
148dynamically typed
149language with the efficiency and safety of a statically typed, compiled language.
150It also aims to be modern, with support for networked and multicore
151computing. Finally, it is intended to be <i>fast</i>: it should take
152at most a few seconds to build a large executable on a single computer.
153To meet these goals required addressing a number of
154linguistic issues: an expressive but lightweight type system;
155concurrency and garbage collection; rigid dependency specification;
156and so on. These cannot be addressed well by libraries or tools; a new
157language was called for.
158</p>
159
Rob Pike48ecfc92013-03-27 15:26:57 -0700160<p>
161The article <a href="http://talks.golang.org/2012/splash.article">Go at Google</a>
162discusses the background and motivation behind the design of the Go language,
163as well as providing more detail about many of the answers presented in this FAQ.
164</p>
165
Andrew Gerrand4164d602010-09-29 16:52:22 +1000166<h3 id="ancestors">
167What are Go's ancestors?</h3>
168<p>
169Go is mostly in the C family (basic syntax),
170with significant input from the Pascal/Modula/Oberon
171family (declarations, packages),
172plus some ideas from languages
173inspired by Tony Hoare's CSP,
174such as Newsqueak and Limbo (concurrency).
175However, it is a new language across the board.
176In every respect the language was designed by thinking
177about what programmers do and how to make programming, at least the
178kind of programming we do, more effective, which means more fun.
179</p>
180
Andrew Gerrand4164d602010-09-29 16:52:22 +1000181<h3 id="principles">
182What are the guiding principles in the design?</h3>
183<p>
184Programming today involves too much bookkeeping, repetition, and
185clerical work. As Dick Gabriel says, &ldquo;Old programs read
186like quiet conversations between a well-spoken research worker and a
187well-studied mechanical colleague, not as a debate with a compiler.
188Who'd have guessed sophistication bought such noise?&rdquo;
189The sophistication is worthwhile&mdash;no one wants to go back to
190the old languages&mdash;but can it be more quietly achieved?
191</p>
192<p>
193Go attempts to reduce the amount of typing in both senses of the word.
194Throughout its design, we have tried to reduce clutter and
195complexity. There are no forward declarations and no header files;
196everything is declared exactly once. Initialization is expressive,
197automatic, and easy to use. Syntax is clean and light on keywords.
198Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
199simple type derivation using the <code>:=</code>
200declare-and-initialize construct. And perhaps most radically, there
201is no type hierarchy: types just <i>are</i>, they don't have to
202announce their relationships. These simplifications allow Go to be
203expressive yet comprehensible without sacrificing, well, sophistication.
204</p>
205<p>
206Another important principle is to keep the concepts orthogonal.
207Methods can be implemented for any type; structures represent data while
208interfaces represent abstraction; and so on. Orthogonality makes it
209easier to understand what happens when things combine.
210</p>
211
Russ Cox32274452009-10-22 00:13:51 -0700212<h2 id="Usage">Usage</h2>
213
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000214<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800215
Evan Shaw64d85762011-05-22 14:56:12 +1000216<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100217Yes. There are now several Go programs deployed in
Rob Pikefcfed142012-01-23 08:39:53 -0800218production inside Google. A public example is the server behind
219<a href="http://golang.org">http://golang.org</a>.
220It's just the <a href="/cmd/godoc"><code>godoc</code></a>
221document server running in a production configuration on
Dave Cheney82cbcb02012-07-11 09:41:08 -0700222<a href="https://developers.google.com/appengine/">Google App Engine</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000223</p>
Rob Pike7685a672009-11-09 20:25:45 -0800224
Rob Pike48ecfc92013-03-27 15:26:57 -0700225<p>
226Other examples include the <a href="https://code.google.com/p/vitess/">Vitess</a>
227system for large-scale SQL installations and Google's download server, <code>dl.google.com</code>,
228which delivers Chrome binaries and other large installables such as <code>apt-get</code>
229packages.
230</p>
231
Russ Cox32274452009-10-22 00:13:51 -0700232<h3 id="Do_Go_programs_link_with_Cpp_programs">
233Do Go programs link with C/C++ programs?</h3>
234
235<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +1100236There are two Go compiler implementations, <code>gc</code>
237(the <code>6g</code> program and friends) and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800238<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700239therefore only be linked with C programs using the same convention.
Oling Cat018e89f2013-01-24 20:46:33 +1100240There is such a C compiler but no C++ compiler.
241<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
242GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000243</p>
Russ Cox32274452009-10-22 00:13:51 -0700244
245<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100246The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
247&ldquo;foreign function interface&rdquo; to allow safe calling of
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000248C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000249</p>
250
Russ Cox32274452009-10-22 00:13:51 -0700251
Rob Pike0c2a4792009-11-01 20:50:42 -0800252<h3 id="Does_Go_support_Google_protocol_buffers">
253Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700254
255<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700256A separate open source project provides the necessary compiler plugin and library.
257It is available at
258<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
259</p>
Russ Cox32274452009-10-22 00:13:51 -0700260
Evan Shaw64d85762011-05-22 14:56:12 +1000261
Russ Cox6301fb42009-12-03 17:23:33 -0800262<h3 id="Can_I_translate_the_Go_home_page">
263Can I translate the Go home page into another language?</h3>
264
265<p>
266Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000267However, if you choose to add the Google logo or branding to your site
Russ Cox6301fb42009-12-03 17:23:33 -0800268(it does not appear on <a href="http://golang.org/">golang.org</a>),
269you will need to abide by the guidelines at
270<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
271</p>
272
Russ Cox32274452009-10-22 00:13:51 -0700273<h2 id="Design">Design</h2>
274
Andrew Gerrand4164d602010-09-29 16:52:22 +1000275<h3 id="unicode_identifiers">
276What's up with Unicode identifiers?</h3>
277
278<p>
279It was important to us to extend the space of identifiers from the
280confines of ASCII. Go's rule&mdash;identifier characters must be
281letters or digits as defined by Unicode&mdash;is simple to understand
282and to implement but has restrictions. Combining characters are
283excluded by design, for instance.
284Until there
285is an agreed external definition of what an identifier might be,
286plus a definition of canonicalization of identifiers that guarantees
287no ambiguity, it seemed better to keep combining characters out of
288the mix. Thus we have a simple rule that can be expanded later
289without breaking programs, one that avoids bugs that would surely arise
290from a rule that admits ambiguous identifiers.
291</p>
292
293<p>
294On a related note, since an exported identifier must begin with an
295upper-case letter, identifiers created from &ldquo;letters&rdquo;
296in some languages can, by definition, not be exported. For now the
297only solution is to use something like <code>X日本語</code>, which
298is clearly unsatisfactory; we are considering other options. The
299case-for-visibility rule is unlikely to change however; it's one
300of our favorite features of Go.
301</p>
302
303<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700304
305<p>
306Every language contains novel features and omits someone's favorite
307feature. Go was designed with an eye on felicity of programming, speed of
308compilation, orthogonality of concepts, and the need to support features
309such as concurrency and garbage collection. Your favorite feature may be
310missing because it doesn't fit, because it affects compilation speed or
311clarity of design, or because it would make the fundamental system model
312too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000313</p>
Russ Cox32274452009-10-22 00:13:51 -0700314
315<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800316If it bothers you that Go is missing feature <var>X</var>,
317please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700318they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000319</p>
Russ Cox32274452009-10-22 00:13:51 -0700320
Andrew Gerrand4164d602010-09-29 16:52:22 +1000321<h3 id="generics">
322Why does Go not have generic types?</h3>
323<p>
324Generics may well be added at some point. We don't feel an urgency for
325them, although we understand some programmers do.
326</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000327
Andrew Gerrand4164d602010-09-29 16:52:22 +1000328<p>
329Generics are convenient but they come at a cost in
330complexity in the type system and run-time. We haven't yet found a
331design that gives value proportionate to the complexity, although we
332continue to think about it. Meanwhile, Go's built-in maps and slices,
333plus the ability to use the empty interface to construct containers
334(with explicit unboxing) mean in many cases it is possible to write
335code that does what generics would enable, if less smoothly.
336</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000337
Andrew Gerrand4164d602010-09-29 16:52:22 +1000338<p>
339This remains an open issue.
340</p>
341
342<h3 id="exceptions">
343Why does Go not have exceptions?</h3>
344<p>
345We believe that coupling exceptions to a control
346structure, as in the <code>try-catch-finally</code> idiom, results in
347convoluted code. It also tends to encourage programmers to label
348too many ordinary errors, such as failing to open a file, as
349exceptional.
350</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000351
Andrew Gerrand4164d602010-09-29 16:52:22 +1000352<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000353Go takes a different approach. For plain error handling, Go's multi-value
354returns make it easy to report an error without overloading the return value.
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100355<a href="/doc/articles/error_handling.html">A canonical error type, coupled
356with Go's other features</a>, makes error handling pleasant but quite different
357from that in other languages.
Rob Pike93c4a242011-08-06 07:41:55 +1000358</p>
359
360<p>
361Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000362of built-in functions to signal and recover from truly exceptional
363conditions. The recovery mechanism is executed only as part of a
364function's state being torn down after an error, which is sufficient
365to handle catastrophe but requires no extra control structures and,
366when used well, can result in clean error-handling code.
367</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000368
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000369<p>
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100370See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000371</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000372
Andrew Gerrand4164d602010-09-29 16:52:22 +1000373<h3 id="assertions">
374Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700375
376<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000377Go doesn't provide assertions. They are undeniably convenient, but our
378experience has been that programmers use them as a crutch to avoid thinking
379about proper error handling and reporting. Proper error handling means that
380servers continue operation after non-fatal errors instead of crashing.
381Proper error reporting means that errors are direct and to the point,
382saving the programmer from interpreting a large crash trace. Precise
383errors are particularly important when the programmer seeing the errors is
384not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000385</p>
Russ Cox32274452009-10-22 00:13:51 -0700386
Andrew Gerrand4164d602010-09-29 16:52:22 +1000387<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000388We understand that this is a point of contention. There are many things in
389the Go language and libraries that differ from modern practices, simply
390because we feel it's sometimes worth trying a different approach.
Evan Shaw64d85762011-05-22 14:56:12 +1000391</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000392
393<h3 id="csp">
394Why build concurrency on the ideas of CSP?</h3>
395<p>
396Concurrency and multi-threaded programming have a reputation
Rob Pikefcfed142012-01-23 08:39:53 -0800397for difficulty. We believe this is due partly to complex
Andrew Gerrand4164d602010-09-29 16:52:22 +1000398designs such as pthreads and partly to overemphasis on low-level details
Rob Pike93c4a242011-08-06 07:41:55 +1000399such as mutexes, condition variables, and memory barriers.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000400Higher-level interfaces enable much simpler code, even if there are still
401mutexes and such under the covers.
402</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000403
Andrew Gerrand4164d602010-09-29 16:52:22 +1000404<p>
405One of the most successful models for providing high-level linguistic support
406for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
407Occam and Erlang are two well known languages that stem from CSP.
408Go's concurrency primitives derive from a different part of the family tree
409whose main contribution is the powerful notion of channels as first class objects.
Rob Pike48ecfc92013-03-27 15:26:57 -0700410Experience with several earlier languages has shown that the CSP model
411fits well into a procedural language framework.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000412</p>
413
414<h3 id="goroutines">
415Why goroutines instead of threads?</h3>
416<p>
417Goroutines are part of making concurrency easy to use. The idea, which has
418been around for a while, is to multiplex independently executing
Rob Pike93c4a242011-08-06 07:41:55 +1000419functions&mdash;coroutines&mdash;onto a set of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000420When a coroutine blocks, such as by calling a blocking system call,
421the run-time automatically moves other coroutines on the same operating
422system thread to a different, runnable thread so they won't be blocked.
423The programmer sees none of this, which is the point.
424The result, which we call goroutines, can be very cheap: unless they spend a lot of time
425in long-running system calls, they cost little more than the memory
Rob Pike93c4a242011-08-06 07:41:55 +1000426for the stack, which is just a few kilobytes.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000427</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000428
Andrew Gerrand4164d602010-09-29 16:52:22 +1000429<p>
430To make the stacks small, Go's run-time uses segmented stacks. A newly
431minted goroutine is given a few kilobytes, which is almost always enough.
432When it isn't, the run-time allocates (and frees) extension segments automatically.
433The overhead averages about three cheap instructions per function call.
434It is practical to create hundreds of thousands of goroutines in the same
435address space. If goroutines were just threads, system resources would
436run out at a much smaller number.
437</p>
438
439<h3 id="atomic_maps">
440Why are map operations not defined to be atomic?</h3>
441
442<p>
443After long discussion it was decided that the typical use of maps did not require
444safe access from multiple threads, and in those cases where it did, the map was
445probably part of some larger data structure or computation that was already
446synchronized. Therefore requiring that all map operations grab a mutex would slow
447down most programs and add safety to few. This was not an easy decision,
448however, since it means uncontrolled map access can crash the program.
449</p>
450
451<p>
452The language does not preclude atomic map updates. When required, such
453as when hosting an untrusted program, the implementation could interlock
454map access.
455</p>
456
Andrew Gerrand4164d602010-09-29 16:52:22 +1000457<h2 id="types">Types</h2>
Russ Cox32274452009-10-22 00:13:51 -0700458
459<h3 id="Is_Go_an_object-oriented_language">
460Is Go an object-oriented language?</h3>
461
462<p>
463Yes and no. Although Go has types and methods and allows an
464object-oriented style of programming, there is no type hierarchy.
Russ Coxe434f1a2009-11-07 17:31:22 -0800465The concept of &ldquo;interface&rdquo; in Go provides a different approach that
Russ Cox32274452009-10-22 00:13:51 -0700466we believe is easy to use and in some ways more general. There are
467also ways to embed types in other types to provide something
468analogous&mdash;but not identical&mdash;to subclassing.
Rob Pike0c2a4792009-11-01 20:50:42 -0800469Moreover, methods in Go are more general than in C++ or Java:
Rob Pikefcfed142012-01-23 08:39:53 -0800470they can be defined for any sort of data, even built-in types such
471as plain, &ldquo;unboxed&rdquo; integers.
472They are not restricted to structs (classes).
Evan Shaw64d85762011-05-22 14:56:12 +1000473</p>
Russ Cox32274452009-10-22 00:13:51 -0700474
475<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800476Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800477lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000478</p>
Russ Cox32274452009-10-22 00:13:51 -0700479
480<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
481How do I get dynamic dispatch of methods?</h3>
482
483<p>
484The only way to have dynamically dispatched methods is through an
Rob Pikefcfed142012-01-23 08:39:53 -0800485interface. Methods on a struct or any other concrete type are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000486</p>
Russ Cox32274452009-10-22 00:13:51 -0700487
Andrew Gerrand4164d602010-09-29 16:52:22 +1000488<h3 id="inheritance">
489Why is there no type inheritance?</h3>
490<p>
491Object-oriented programming, at least in the best-known languages,
492involves too much discussion of the relationships between types,
493relationships that often could be derived automatically. Go takes a
494different approach.
495</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000496
Andrew Gerrand4164d602010-09-29 16:52:22 +1000497<p>
498Rather than requiring the programmer to declare ahead of time that two
499types are related, in Go a type automatically satisfies any interface
500that specifies a subset of its methods. Besides reducing the
501bookkeeping, this approach has real advantages. Types can satisfy
502many interfaces at once, without the complexities of traditional
503multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000504Interfaces can be very lightweight&mdash;an interface with
505one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000506Interfaces can be added after the fact if a new idea comes along
507or for testing&mdash;without annotating the original types.
508Because there are no explicit relationships between types
509and interfaces, there is no type hierarchy to manage or discuss.
510</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000511
Andrew Gerrand4164d602010-09-29 16:52:22 +1000512<p>
513It's possible to use these ideas to construct something analogous to
514type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
515enables formatted printing to any output, not just a file, or how the
516<code>bufio</code> package can be completely separate from file I/O,
Rob Pike86494442011-11-08 16:26:03 -0800517or how the <code>image</code> packages generate compressed
518image files. All these ideas stem from a single interface
Andrew Gerrand4164d602010-09-29 16:52:22 +1000519(<code>io.Writer</code>) representing a single method
520(<code>Write</code>). And that's only scratching the surface.
Rob Pike5cff1902012-02-20 12:42:50 +1100521Go's interfaces have a profound influence on how programs are structured.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000522</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000523
Andrew Gerrand4164d602010-09-29 16:52:22 +1000524<p>
525It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000526dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000527</p>
528
529<h3 id="methods_on_basics">
530Why is <code>len</code> a function and not a method?</h3>
531<p>
532We debated this issue but decided
533implementing <code>len</code> and friends as functions was fine in practice and
534didn't complicate questions about the interface (in the Go type sense)
535of basic types.
536</p>
537
538<h3 id="overloading">
539Why does Go not support overloading of methods and operators?</h3>
540<p>
541Method dispatch is simplified if it doesn't need to do type matching as well.
542Experience with other languages told us that having a variety of
543methods with the same name but different signatures was occasionally useful
544but that it could also be confusing and fragile in practice. Matching only by name
545and requiring consistency in the types was a major simplifying decision
546in Go's type system.
547</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000548
Andrew Gerrand4164d602010-09-29 16:52:22 +1000549<p>
550Regarding operator overloading, it seems more a convenience than an absolute
551requirement. Again, things are simpler without it.
552</p>
553
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100554<h3 id="implements_interface">
555Why doesn't Go have "implements" declarations?</h3>
556
557<p>
558A Go type satisfies an interface by implementing the methods of that interface,
559nothing more. This property allows interfaces to be defined and used without
Rob Pike4be9b832012-09-07 14:01:02 -0700560having to modify existing code. It enables a kind of structural typing that
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100561promotes separation of concerns and improves code re-use, and makes it easier
562to build on patterns that emerge as the code develops.
563The semantics of interfaces is one of the main reasons for Go's nimble,
564lightweight feel.
565</p>
566
567<p>
568See the <a href="#inheritance">question on type inheritance</a> for more detail.
569</p>
570
571<h3 id="guarantee_satisfies_interface">
572How can I guarantee my type satisfies an interface?</h3>
573
574<p>
575You can ask the compiler to check that the type <code>T</code> implements the
576interface <code>I</code> by attempting an assignment:
577</p>
578
579<pre>
580type T struct{}
Rob Pikefcfed142012-01-23 08:39:53 -0800581var _ I = T{} // Verify that T implements I.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100582</pre>
583
584<p>
585If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
586at compile time.
587</p>
588
589<p>
590If you wish the users of an interface to explicitly declare that they implement
591it, you can add a method with a descriptive name to the interface's method set.
592For example:
593</p>
594
595<pre>
596type Fooer interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800597 Foo()
598 ImplementsFooer()
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100599}
600</pre>
601
602<p>
603A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100604<code>Fooer</code>, clearly documenting the fact and announcing it in
605<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100606</p>
607
608<pre>
609type Bar struct{}
610func (b Bar) ImplementsFooer() {}
611func (b Bar) Foo() {}
612</pre>
613
614<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100615Most code doesn't make use of such constraints, since they limit the utility of
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100616the interface idea. Sometimes, though, they're necessary to resolve ambiguities
617among similar interfaces.
618</p>
619
Rob Pike93c4a242011-08-06 07:41:55 +1000620<h3 id="t_and_equal_interface">
621Why doesn't type T satisfy the Equal interface?</h3>
622
623<p>
624Consider this simple interface to represent an object that can compare
625itself with another value:
626</p>
627
628<pre>
629type Equaler interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800630 Equal(Equaler) bool
Rob Pike93c4a242011-08-06 07:41:55 +1000631}
632</pre>
633
634<p>
635and this type, <code>T</code>:
636</p>
637
638<pre>
639type T int
640func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
641</pre>
642
643<p>
644Unlike the analogous situation in some polymorphic type systems,
645<code>T</code> does not implement <code>Equaler</code>.
646The argument type of <code>T.Equal</code> is <code>T</code>,
647not literally the required type <code>Equaler</code>.
648</p>
649
650<p>
651In Go, the type system does not promote the argument of
652<code>Equal</code>; that is the programmer's responsibility, as
653illustrated by the type <code>T2</code>, which does implement
654<code>Equaler</code>:
655</p>
656
657<pre>
658type T2 int
659func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
660</pre>
661
662<p>
663Even this isn't like other type systems, though, because in Go <em>any</em>
664type that satisfies <code>Equaler</code> could be passed as the
665argument to <code>T2.Equal</code>, and at run time we must
666check that the argument is of type <code>T2</code>.
667Some languages arrange to make that guarantee at compile time.
668</p>
669
670<p>
671A related example goes the other way:
672</p>
673
674<pre>
675type Opener interface {
676 Open(name) Reader
677}
678
679func (t T3) Open() *os.File
680</pre>
681
682<p>
683In Go, <code>T3</code> does not satisfy <code>Opener</code>,
684although it might in another language.
685</p>
686
687<p>
688While it is true that Go's type system does less for the programmer
689in such cases, the lack of subtyping makes the rules about
690interface satisfaction very easy to state: are the function's names
691and signatures exactly those of the interface?
692Go's rule is also easy to implement efficiently.
693We feel these benefits offset the lack of
694automatic type promotion. Should Go one day adopt some form of generic
695typing, we expect there would be a way to express the idea of these
696examples and also have them be statically checked.
697</p>
698
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000699<h3 id="convert_slice_of_interface">
700Can I convert a []T to an []interface{}?</h3>
701
702<p>
Rob Pike86494442011-11-08 16:26:03 -0800703Not directly, because they do not have the same representation in memory.
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000704It is necessary to copy the elements individually to the destination
705slice. This example converts a slice of <code>int</code> to a slice of
706<code>interface{}</code>:
707</p>
708
709<pre>
710t := []int{1, 2, 3, 4}
711s := make([]interface{}, len(t))
712for i, v := range t {
Rob Pikefcfed142012-01-23 08:39:53 -0800713 s[i] = v
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000714}
715</pre>
716
Rob Pike1e0f97a2012-02-17 16:27:17 +1100717<h3 id="nil_error">
718Why is my nil error value not equal to nil?
719</h3>
720
721<p>
722Under the covers, interfaces are implemented as two elements, a type and a value.
723The value, called the interface's dynamic value,
724is an arbitrary concrete value and the type is that of the value.
725For the <code>int</code> value 3, an interface value contains,
726schematically, (<code>int</code>, <code>3</code>).
727</p>
728
729<p>
730An interface value is <code>nil</code> only if the inner value and type are both unset,
731(<code>nil</code>, <code>nil</code>).
732In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
733If we store a pointer of type <code>*int</code> inside
734an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
735(<code>*int</code>, <code>nil</code>).
736Such an interface value will therefore be non-<code>nil</code>
737<em>even when the pointer inside is</em> <code>nil</code>.
738</p>
739
740<p>
741This situation can be confusing, and often arises when a <code>nil</code> value is
742stored inside an interface value such as an <code>error</code> return:
743</p>
744
745<pre>
746func returnsError() error {
747 var p *MyError = nil
748 if bad() {
749 p = ErrBad
750 }
751 return p // Will always return a non-nil error.
752}
753</pre>
754
755<p>
756If all goes well, the function returns a <code>nil</code> <code>p</code>,
757so the return value is an <code>error</code> interface
758value holding (<code>*MyError</code>, <code>nil</code>).
759This means that if the caller compares the returned error to <code>nil</code>,
760it will always look as if there was an error even if nothing bad happened.
761To return a proper <code>nil</code> <code>error</code> to the caller,
762the function must return an explicit <code>nil</code>:
763</p>
764
765
766<pre>
767func returnsError() error {
768 if bad() {
769 return ErrBad
770 }
771 return nil
772}
773</pre>
774
775<p>
776It's a good idea for functions
777that return errors always to use the <code>error</code> type in
778their signature (as we did above) rather than a concrete type such
779as <code>*MyError</code>, to help guarantee the error is
780created correctly. As an example,
781<a href="/pkg/os/#Open"><code>os.Open</code></a>
782returns an <code>error</code> even though, if not <code>nil</code>,
783it's always of concrete type
784<a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
785</p>
786
787<p>
788Similar situations to those described here can arise whenever interfaces are used.
789Just keep in mind that if any concrete value
790has been stored in the interface, the interface will not be <code>nil</code>.
791For more information, see
Shenghou Macb6c09a2012-03-01 14:54:35 +0800792<a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
Rob Pike1e0f97a2012-02-17 16:27:17 +1100793</p>
794
795
Rob Pike7d87f3d2011-08-06 11:21:59 +1000796<h3 id="unions">
797Why are there no untagged unions, as in C?</h3>
798
799<p>
800Untagged unions would violate Go's memory safety
801guarantees.
802</p>
803
804<h3 id="variant_types">
805Why does Go not have variant types?</h3>
806
807<p>
808Variant types, also known as algebraic types, provide a way to specify
809that a value might take one of a set of other types, but only those
810types. A common example in systems programming would specify that an
811error is, say, a network error, a security error or an application
812error and allow the caller to discriminate the source of the problem
813by examining the type of the error. Another example is a syntax tree
814in which each node can be a different type: declaration, statement,
815assignment and so on.
816</p>
817
818<p>
819We considered adding variant types to Go, but after discussion
820decided to leave them out because they overlap in confusing ways
821with interfaces. What would happen if the elements of a variant type
822were themselves interfaces?
823</p>
824
825<p>
826Also, some of what variant types address is already covered by the
827language. The error example is easy to express using an interface
828value to hold the error and a type switch to discriminate cases. The
829syntax tree example is also doable, although not as elegantly.
830</p>
831
Andrew Gerrand4164d602010-09-29 16:52:22 +1000832<h2 id="values">Values</h2>
833
834<h3 id="conversions">
835Why does Go not provide implicit numeric conversions?</h3>
836<p>
837The convenience of automatic conversion between numeric types in C is
838outweighed by the confusion it causes. When is an expression unsigned?
839How big is the value? Does it overflow? Is the result portable, independent
840of the machine on which it executes?
841It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
842are not easy to implement and inconsistent across architectures.
843For reasons of portability, we decided to make things clear and straightforward
844at the cost of some explicit conversions in the code.
845The definition of constants in Go&mdash;arbitrary precision values free
846of signedness and size annotations&mdash;ameliorates matters considerably,
847though.
848</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000849
Andrew Gerrand4164d602010-09-29 16:52:22 +1000850<p>
851A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
852are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
853type is generic; if you care about how many bits an integer holds, Go
854encourages you to be explicit.
855</p>
856
857<h3 id="builtin_maps">
858Why are maps built in?</h3>
859<p>
860The same reason strings are: they are such a powerful and important data
861structure that providing one excellent implementation with syntactic support
862makes programming more pleasant. We believe that Go's implementation of maps
863is strong enough that it will serve for the vast majority of uses.
864If a specific application can benefit from a custom implementation, it's possible
865to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
866</p>
867
Andrew Gerrand4164d602010-09-29 16:52:22 +1000868<h3 id="map_keys">
Rob Pikefcfed142012-01-23 08:39:53 -0800869Why don't maps allow slices as keys?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000870<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800871Map lookup requires an equality operator, which slices do not implement.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000872They don't implement equality because equality is not well defined on such types;
873there are multiple considerations involving shallow vs. deep comparison, pointer vs.
Rob Pikefcfed142012-01-23 08:39:53 -0800874value comparison, how to deal with recursive types, and so on.
875We may revisit this issue&mdash;and implementing equality for slices
Andrew Gerrand4164d602010-09-29 16:52:22 +1000876will not invalidate any existing programs&mdash;but without a clear idea of what
Rob Pike5cff1902012-02-20 12:42:50 +1100877equality of slices should mean, it was simpler to leave it out for now.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000878</p>
879
Rob Pikefcfed142012-01-23 08:39:53 -0800880<p>
Rob Pike5cff1902012-02-20 12:42:50 +1100881In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
882types can be used as map keys. Slices still do not have a definition of equality, though.
Rob Pikefcfed142012-01-23 08:39:53 -0800883</p>
884
Andrew Gerrand4164d602010-09-29 16:52:22 +1000885<h3 id="references">
886Why are maps, slices, and channels references while arrays are values?</h3>
887<p>
888There's a lot of history on that topic. Early on, maps and channels
889were syntactically pointers and it was impossible to declare or use a
890non-pointer instance. Also, we struggled with how arrays should work.
891Eventually we decided that the strict separation of pointers and
Rob Pike48ecfc92013-03-27 15:26:57 -0700892values made the language harder to use. Changing these
893types to act as references to the associated, shared data structures resolved
894these issues. This change added some regrettable complexity to the
895language but had a large effect on usability: Go became a more
896productive, comfortable language when it was introduced.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000897</p>
898
Russ Cox32274452009-10-22 00:13:51 -0700899<h2 id="Writing_Code">Writing Code</h2>
900
901<h3 id="How_are_libraries_documented">
902How are libraries documented?</h3>
903
904<p>
905There is a program, <code>godoc</code>, written in Go, that extracts
906package documentation from the source code. It can be used on the
907command line or on the web. An instance is running at
Rob Pike0c2a4792009-11-01 20:50:42 -0800908<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -0800909In fact, <code>godoc</code> implements the full site at
Rob Pike0c2a4792009-11-01 20:50:42 -0800910<a href="http://golang.org/">http://golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000911</p>
Russ Cox32274452009-10-22 00:13:51 -0700912
913<h3 id="Is_there_a_Go_programming_style_guide">
914Is there a Go programming style guide?</h3>
915
916<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800917Eventually, there may be a small number of rules to guide things
918like naming, layout, and file organization.
919The document <a href="effective_go.html">Effective Go</a>
920contains some style advice.
921More directly, the program <code>gofmt</code> is a pretty-printer
922whose purpose is to enforce layout rules; it replaces the usual
923compendium of do's and don'ts that allows interpretation.
924All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +1000925</p>
Russ Cox32274452009-10-22 00:13:51 -0700926
927<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
928How do I submit patches to the Go libraries?</h3>
929
Rob Pike0c2a4792009-11-01 20:50:42 -0800930<p>
931The library sources are in <code>go/src/pkg</code>.
932If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +1000933</p>
Russ Cox32274452009-10-22 00:13:51 -0700934
Rob Pike0c2a4792009-11-01 20:50:42 -0800935<p>
936See the document
937<a href="contribute.html">Contributing to the Go project</a>
938for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +1000939</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000940
Rob Pike91f2a342012-09-07 11:19:01 -0700941<h3 id="Why_does_the_project_use_Mercurial_and_not_git">
942Why does the project use Mercurial and not git?</h3>
943
944<p>
945The Go project, hosted by Google Code at
946<a href="http://code.google.com/p/go">code.google.com/p/go</a>,
947uses Mercurial as its version control system.
948When the project launched,
949Google Code supported only Subversion and Mercurial.
950Mercurial was a better choice because of its plugin mechanism
951that allowed us to create the "codereview" plugin to connect
Oling Cat018e89f2013-01-24 20:46:33 +1100952the project to the excellent code review tools at
Rob Pike91f2a342012-09-07 11:19:01 -0700953<a href="http://codereview.appspot.com">codereview.appspot.com</a>.
954</p>
955
956<p>
957Programmers who work
958with the Go project's source rather than release downloads sometimes
959ask for the project to switch to git.
960That would be possible, but it would be a lot of work and
961would also require reimplementing the codereview plugin.
962Given that Mercurial works today, with code review support,
963combined with the Go project's mostly linear, non-branching use of
964version control, a switch to git doesn't seem worthwhile.
965</p>
966
Herbert Georg Fischer99021b72013-03-15 13:43:10 -0700967<h3 id="git_https">
968Why does "go get" use HTTPS when cloning a repository?</h3>
969
970<p>
971Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
972and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418
973(git) and TCP port 22 (SSH).
974When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
975default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
976The <code>go get</code> command therefore uses HTTPS for safety.
977</p>
978
979<p>
980If you use <code>git</code> and prefer to push changes through SSH using your existing key
981it's easy to work around this. For GitHub, try one of these solutions:
982</p>
983<ul>
984<li>Manually clone the repository in the expected package directory:
985<pre>
986$ cd $GOPATH/src/github.com/username
987$ git clone git@github.com:username/package.git
988</pre>
989</li>
990<li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending
991these two lines to <code>~/.gitconfig</code>:
992<pre>
993[url "git@github.com:"]
994 pushInsteadOf = https://github.com/
995</pre>
996</li>
997</ul>
998
Andrew Gerrand4164d602010-09-29 16:52:22 +1000999<h2 id="Pointers">Pointers and Allocation</h2>
1000
1001<h3 id="pass_by_value">
1002When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001003
1004<p>
Rob Pike86494442011-11-08 16:26:03 -08001005As in all languages in the C family, everything in Go is passed by value.
1006That is, a function always gets a copy of the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001007thing being passed, as if there were an assignment statement assigning the
Rob Pike86494442011-11-08 16:26:03 -08001008value to the parameter. For instance, passing an <code>int</code> value
1009to a function makes a copy of the <code>int</code>, and passing a pointer
1010value makes a copy of the pointer, but not the data it points to.
1011(See the next section for a discussion of how this affects method receivers.)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001012</p>
Russ Cox32274452009-10-22 00:13:51 -07001013
1014<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001015Map and slice values behave like pointers: they are descriptors that
Andrew Gerrand4164d602010-09-29 16:52:22 +10001016contain pointers to the underlying map or slice data. Copying a map or
1017slice value doesn't copy the data it points to. Copying an interface value
1018makes a copy of the thing stored in the interface value. If the interface
1019value holds a struct, copying the interface value makes a copy of the
1020struct. If the interface value holds a pointer, copying the interface value
Oling Cat018e89f2013-01-24 20:46:33 +11001021makes a copy of the pointer, but again not the data it points to.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001022</p>
1023
Rob Pike09cd13c2013-03-15 11:38:50 -07001024<h3 id="pointer_to_interface">
1025When should I use a pointer to an interface?</h3>
1026
1027<p>
1028Almost never. Pointers to interface values arise only in rare, tricky situations involving
1029disguising an interface value's type for delayed evaluation.
1030</p>
1031
1032<p>
1033It is however a common mistake to pass a pointer to an interface value
1034to a function expecting an interface. The compiler will complain about this
1035error but the situation can still be confusing, because sometimes a
1036<a href="#different_method_sets">pointer
1037is necessary to satisfy an interface</a>.
1038The insight is that although a pointer to a concrete type can satisfy
1039an interface, with one exception <em>a pointer to an interface can never satisfy a interface</em>.
1040</p>
1041
1042<p>
1043Consider the variable declaration,
1044</p>
1045
1046<pre>
1047var w io.Writer
1048</pre>
1049
1050<p>
1051The printing function <code>fmt.Fprintf</code> takes as its first argument
1052a value that satisfies <code>io.Writer</code>—something that implements
1053the canonical <code>Write</code> method. Thus we can write
1054</p>
1055
1056<pre>
1057fmt.Fprintf(w, "hello, world\n")
1058</pre>
1059
1060<p>
1061If however we pass the address of <code>w</code>, the program will not compile.
1062</p>
1063
1064<pre>
1065fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
1066</pre>
1067
1068<p>
1069The one exception is that any value, even a pointer to an interface, can be assigned to
1070a variable of empty interface type (<code>interface{}</code>).
1071Even so, it's almost certainly a mistake if the value is a pointer to an interface;
1072the result can be confusing.
1073</p>
1074
Andrew Gerrand4164d602010-09-29 16:52:22 +10001075<h3 id="methods_on_values_or_pointers">
1076Should I define methods on values or pointers?</h3>
1077
1078<pre>
Rob Pike93c4a242011-08-06 07:41:55 +10001079func (s *MyStruct) pointerMethod() { } // method on pointer
1080func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +10001081</pre>
Russ Cox32274452009-10-22 00:13:51 -07001082
1083<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001084For programmers unaccustomed to pointers, the distinction between these
1085two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001086When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike5cff1902012-02-20 12:42:50 +11001087examples) behaves exactly as if it were an argument to the method.
Rob Pike93c4a242011-08-06 07:41:55 +10001088Whether to define the receiver as a value or as a pointer is the same
1089question, then, as whether a function argument should be a value or
1090a pointer.
1091There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001092</p>
1093
Rob Pike93c4a242011-08-06 07:41:55 +10001094<p>
1095First, and most important, does the method need to modify the
1096receiver?
1097If it does, the receiver <em>must</em> be a pointer.
Rob Pike48ecfc92013-03-27 15:26:57 -07001098(Slices and maps act as references, so their story is a little
Rob Pike93c4a242011-08-06 07:41:55 +10001099more subtle, but for instance to change the length of a slice
1100in a method the receiver must still be a pointer.)
1101In the examples above, if <code>pointerMethod</code> modifies
1102the fields of <code>s</code>,
1103the caller will see those changes, but <code>valueMethod</code>
1104is called with a copy of the caller's argument (that's the definition
1105of passing a value), so changes it makes will be invisible to the caller.
1106</p>
1107
1108<p>
1109By the way, pointer receivers are identical to the situation in Java,
1110although in Java the pointers are hidden under the covers; it's Go's
1111value receivers that are unusual.
1112</p>
1113
1114<p>
1115Second is the consideration of efficiency. If the receiver is large,
1116a big <code>struct</code> for instance, it will be much cheaper to
1117use a pointer receiver.
1118</p>
1119
1120<p>
1121Next is consistency. If some of the methods of the type must have
1122pointer receivers, the rest should too, so the method set is
1123consistent regardless of how the type is used.
1124See the section on <a href="#different_method_sets">method sets</a>
1125for details.
1126</p>
1127
1128<p>
1129For types such as basic types, slices, and small <code>structs</code>,
1130a value receiver is very cheap so unless the semantics of the method
1131requires a pointer, a value receiver is efficient and clear.
1132</p>
1133
1134
Andrew Gerrand4164d602010-09-29 16:52:22 +10001135<h3 id="new_and_make">
1136What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001137
1138<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001139In short: <code>new</code> allocates memory, <code>make</code> initializes
1140the slice, map, and channel types.
1141</p>
1142
1143<p>
1144See the <a href="/doc/effective_go.html#allocation_new">relevant section
1145of Effective Go</a> for more details.
1146</p>
1147
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +11001148<h3 id="q_int_sizes">
Rob Pike48ecfc92013-03-27 15:26:57 -07001149What is the size of an <code>int</code> on a 64 bit machine?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001150
1151<p>
Rob Pike80e25fc2011-01-19 23:07:38 -05001152The sizes of <code>int</code> and <code>uint</code> are implementation-specific
1153but the same as each other on a given platform.
Russ Cox10ea6512012-09-24 20:57:01 -04001154For portability, code that relies on a particular
Rob Pike80e25fc2011-01-19 23:07:38 -05001155size of value should use an explicitly sized type, like <code>int64</code>.
Russ Cox10ea6512012-09-24 20:57:01 -04001156Prior to Go 1.1, the 64-bit Go compilers (both gc and gccgo) used
1157a 32-bit representation for <code>int</code>. As of Go 1.1 they use
1158a 64-bit representation.
Rob Pike80e25fc2011-01-19 23:07:38 -05001159On the other hand, floating-point scalars and complex
1160numbers are always sized: <code>float32</code>, <code>complex64</code>,
1161etc., because programmers should be aware of precision when using
1162floating-point numbers.
1163The default size of a floating-point constant is <code>float64</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001164</p>
1165
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001166<h3 id="stack_or_heap">
1167How do I know whether a variable is allocated on the heap or the stack?</h3>
1168
1169<p>
1170From a correctness standpoint, you don't need to know.
1171Each variable in Go exists as long as there are references to it.
1172The storage location chosen by the implementation is irrelevant to the
1173semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +10001174</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001175
1176<p>
1177The storage location does have an effect on writing efficient programs.
1178When possible, the Go compilers will allocate variables that are
1179local to a function in that function's stack frame. However, if the
1180compiler cannot prove that the variable is not referenced after the
1181function returns, then the compiler must allocate the variable on the
1182garbage-collected heap to avoid dangling pointer errors.
Rob Pikefcfed142012-01-23 08:39:53 -08001183Also, if a local variable is very large, it might make more sense
1184to store it on the heap rather than the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001185</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001186
1187<p>
Rob Pike86494442011-11-08 16:26:03 -08001188In the current compilers, if a variable has its address taken, that variable
1189is a candidate for allocation on the heap. However, a basic <em>escape
1190analysis</em> recognizes some cases when such variables will not
1191live past the return from the function and can reside on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001192</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001193
Andrew Gerrand21009472012-10-11 14:21:19 +11001194<h3 id="Why_does_my_Go_process_use_so_much_virtual_memory">
1195Why does my Go process use so much virtual memory?</h3>
1196
1197<p>
1198The Go memory allocator reserves a large region of virtual memory as an arena
1199for allocations. This virtual memory is local to the specific Go process; the
1200reservation does not deprive other processes of memory.
1201</p>
1202
1203<p>
1204To find the amount of actual memory allocated to a Go process, use the Unix
1205<code>top</code> command and consult the <code>RES</code> (Linux) or
1206<code>RSIZE</code> (Mac OS X) columns.
1207<!-- TODO(adg): find out how this works on Windows -->
1208</p>
1209
Andrew Gerrand4164d602010-09-29 16:52:22 +10001210<h2 id="Concurrency">Concurrency</h2>
1211
1212<h3 id="What_operations_are_atomic_What_about_mutexes">
1213What operations are atomic? What about mutexes?</h3>
1214
1215<p>
1216We haven't fully defined it all yet, but some details about atomicity are
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001217available in the <a href="/ref/mem">Go Memory Model specification</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001218</p>
1219
1220<p>
1221Regarding mutexes, the <a href="/pkg/sync">sync</a>
1222package implements them, but we hope Go programming style will
1223encourage people to try higher-level techniques. In particular, consider
1224structuring your program so that only one goroutine at a time is ever
1225responsible for a particular piece of data.
1226</p>
1227
1228<p>
1229Do not communicate by sharing memory. Instead, share memory by communicating.
1230</p>
1231
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001232<p>
1233See 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.
1234</p>
1235
Andrew Gerrand4164d602010-09-29 16:52:22 +10001236<h3 id="Why_no_multi_CPU">
1237Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1238
1239<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001240You must set the <code>GOMAXPROCS</code> shell environment variable
1241or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a>
1242of the runtime package to allow the
Oling Cat018e89f2013-01-24 20:46:33 +11001243run-time support to utilize more than one OS thread.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001244</p>
1245
1246<p>
Rob Pike86494442011-11-08 16:26:03 -08001247Programs that perform parallel computation should benefit from an increase in
Rob Pike5cff1902012-02-20 12:42:50 +11001248<code>GOMAXPROCS</code>.
Rob Pike48ecfc92013-03-27 15:26:57 -07001249However, be aware that
1250<a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">concurrency
1251is not parallelism</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001252</p>
1253
1254<h3 id="Why_GOMAXPROCS">
1255Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
1256slower?</h3>
1257
1258<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001259It depends on the nature of your program.
Rob Pike01afb792012-01-26 14:44:38 -08001260Problems that are intrinsically sequential cannot be sped up by adding
1261more goroutines.
1262Concurrency only becomes parallelism when the problem is
1263intrinsically parallel.
1264</p>
1265
1266<p>
1267In practical terms, programs that spend more time
1268communicating on channels than doing computation
1269will experience performance degradation when using
1270multiple OS threads.
1271This is because sending data between threads involves switching
1272contexts, which has significant cost.
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001273For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
Rob Pike01afb792012-01-26 14:44:38 -08001274from the Go specification has no significant parallelism although it launches many
1275goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than
1276to speed it up.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001277</p>
1278
1279<p>
Rob Pike966bf712011-03-01 13:54:22 -08001280Go's goroutine scheduler is not as good as it needs to be. In future, it
1281should recognize such cases and optimize its use of OS threads. For now,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001282<code>GOMAXPROCS</code> should be set on a per-application basis.
1283</p>
1284
Rob Pike48ecfc92013-03-27 15:26:57 -07001285<p>
1286For more detail on this topic see the talk entitled,
1287<a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency
1288is not Parallelism</a>.
1289
Andrew Gerrand4164d602010-09-29 16:52:22 +10001290<h2 id="Functions_methods">Functions and Methods</h2>
1291
1292<h3 id="different_method_sets">
1293Why do T and *T have different method sets?</h3>
1294
1295<p>
Andrew Gerranda22b0f82012-03-05 15:30:27 +11001296From the <a href="/ref/spec#Types">Go Spec</a>:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001297</p>
1298
1299<blockquote>
1300The method set of any other named type <code>T</code> consists of all methods
1301with receiver type <code>T</code>. The method set of the corresponding pointer
1302type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1303<code>T</code> (that is, it also contains the method set of <code>T</code>).
1304</blockquote>
1305
1306<p>
1307If an interface value contains a pointer <code>*T</code>,
1308a method call can obtain a value by dereferencing the pointer,
1309but if an interface value contains a value <code>T</code>,
1310there is no useful way for a method call to obtain a pointer.
1311</p>
1312
1313<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001314Even in cases where the compiler could take the address of a value
1315to pass to the method, if the method modifies the value the changes
1316will be lost in the caller.
1317As a common example, this code:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001318</p>
1319
1320<pre>
1321var buf bytes.Buffer
1322io.Copy(buf, os.Stdin)
1323</pre>
1324
1325<p>
1326would copy standard input into a <i>copy</i> of <code>buf</code>,
1327not into <code>buf</code> itself.
1328This is almost never the desired behavior.
1329</p>
1330
1331<h3 id="closures_and_goroutines">
Rob Pikefcfed142012-01-23 08:39:53 -08001332What happens with closures running as goroutines?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001333
1334<p>
1335Some confusion may arise when using closures with concurrency.
1336Consider the following program:
1337</p>
1338
1339<pre>
1340func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001341 done := make(chan bool)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001342
Rob Pike5cff1902012-02-20 12:42:50 +11001343 values := []string{"a", "b", "c"}
Rob Pikefcfed142012-01-23 08:39:53 -08001344 for _, v := range values {
1345 go func() {
1346 fmt.Println(v)
1347 done &lt;- true
1348 }()
1349 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001350
Rob Pikefcfed142012-01-23 08:39:53 -08001351 // wait for all goroutines to complete before exiting
1352 for _ = range values {
Oling Cat018e89f2013-01-24 20:46:33 +11001353 &lt;-done
Rob Pikefcfed142012-01-23 08:39:53 -08001354 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001355}
1356</pre>
1357
1358<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001359One might mistakenly expect to see <code>a, b, c</code> as the output.
1360What you'll probably see instead is <code>c, c, c</code>. This is because
Rob Pikefcfed142012-01-23 08:39:53 -08001361each iteration of the loop uses the same instance of the variable <code>v</code>, so
Oling Cat018e89f2013-01-24 20:46:33 +11001362each closure shares that single variable. When the closure runs, it prints the
Rob Pikefcfed142012-01-23 08:39:53 -08001363value of <code>v</code> at the time <code>fmt.Println</code> is executed,
Oling Cat018e89f2013-01-24 20:46:33 +11001364but <code>v</code> may have been modified since the goroutine was launched.
Christian Himpel89ed40c2012-11-12 07:25:54 -08001365To help detect this and other problems before they happen, run
Andrew Gerrand399a36a2013-01-15 19:25:16 +11001366<a href="http://golang.org/cmd/go/#hdr-Run_go_tool_vet_on_packages"><code>go vet</code></a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001367</p>
1368
1369<p>
Rob Pike0cab7d52012-09-07 09:11:39 -07001370To bind the current value of <code>v</code> to each closure as it is launched, one
1371must modify the inner loop to create a new variable each iteration.
1372One way is to pass the variable as an argument to the closure:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001373</p>
1374
1375<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001376 for _, v := range values {
1377 go func(<b>u</b> string) {
1378 fmt.Println(<b>u</b>)
1379 done &lt;- true
1380 }(<b>v</b>)
1381 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001382</pre>
1383
1384<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001385In this example, the value of <code>v</code> is passed as an argument to the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001386anonymous function. That value is then accessible inside the function as
1387the variable <code>u</code>.
1388</p>
1389
Rob Pike0cab7d52012-09-07 09:11:39 -07001390<p>
1391Even easier is just to create a new variable, using a declaration style that may
1392seem odd but works fine in Go:
1393</p>
1394
1395<pre>
1396 for _, v := range values {
1397 <b>v := v</b> // create a new 'v'.
1398 go func() {
1399 fmt.Println(<b>v</b>)
1400 done &lt;- true
1401 }()
1402 }
1403</pre>
1404
Andrew Gerrand4164d602010-09-29 16:52:22 +10001405<h2 id="Control_flow">Control flow</h2>
1406
1407<h3 id="Does_Go_have_a_ternary_form">
1408Does Go have the <code>?:</code> operator?</h3>
1409
1410<p>
1411There is no ternary form in Go. You may use the following to achieve the same
1412result:
1413</p>
1414
1415<pre>
1416if expr {
Rob Pikefcfed142012-01-23 08:39:53 -08001417 n = trueVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001418} else {
Rob Pikefcfed142012-01-23 08:39:53 -08001419 n = falseVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001420}
1421</pre>
1422
1423<h2 id="Packages_Testing">Packages and Testing</h2>
1424
1425<h3 id="How_do_I_create_a_multifile_package">
1426How do I create a multifile package?</h3>
1427
1428<p>
1429Put all the source files for the package in a directory by themselves.
1430Source files can refer to items from different files at will; there is
1431no need for forward declarations or a header file.
1432</p>
1433
1434<p>
1435Other than being split into multiple files, the package will compile and test
1436just like a single-file package.
1437</p>
1438
1439<h3 id="How_do_I_write_a_unit_test">
1440How do I write a unit test?</h3>
1441
1442<p>
1443Create a new file ending in <code>_test.go</code> in the same directory
1444as your package sources. Inside that file, <code>import "testing"</code>
1445and write functions of the form
1446</p>
1447
1448<pre>
1449func TestFoo(t *testing.T) {
1450 ...
1451}
1452</pre>
1453
1454<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001455Run <code>go test</code> in that directory.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001456That script finds the <code>Test</code> functions,
1457builds a test binary, and runs it.
1458</p>
1459
Rob Pike5cff1902012-02-20 12:42:50 +11001460<p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
1461the <a href="/pkg/testing/"><code>testing</code></a> package
Andrew Gerrand399a36a2013-01-15 19:25:16 +11001462and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details.
Rob Pike5cff1902012-02-20 12:42:50 +11001463</p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001464
Rob Pikef6615f12011-11-09 13:19:23 -08001465<h3 id="testing_framework">
1466Where is my favorite helper function for testing?</h3>
1467
1468<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001469Go'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 -08001470features provided in other language's testing frameworks such as assertion functions.
1471An <a href="#assertions">earlier section</a> of this document explained why Go
1472doesn't have assertions, and
1473the same arguments apply to the use of <code>assert</code> in tests.
1474Proper error handling means letting other tests run after one has failed, so
1475that the person debugging the failure gets a complete picture of what is
1476wrong. It is more useful for a test to report that
1477<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
14782, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
1479answer for 2 and therefore no more tests were run. The programmer who
1480triggers the test failure may not be familiar with the code that fails.
1481Time invested writing a good error message now pays off later when the
1482test breaks.
1483</p>
1484
1485<p>
1486A related point is that testing frameworks tend to develop into mini-languages
1487of their own, with conditionals and controls and printing mechanisms,
1488but Go already has all those capabilities; why recreate them?
1489We'd rather write tests in Go; it's one fewer language to learn and the
1490approach keeps the tests straightforward and easy to understand.
1491</p>
1492
1493<p>
1494If the amount of extra code required to write
1495good errors seems repetitive and overwhelming, the test might work better if
1496table-driven, iterating over a list of inputs and outputs defined
1497in a data structure (Go has excellent support for data structure literals).
1498The work to write a good test and good error messages will then be amortized over many
1499test cases. The standard Go library is full of illustrative examples, such as in
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001500<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 -08001501</p>
1502
Russ Cox32274452009-10-22 00:13:51 -07001503
1504<h2 id="Implementation">Implementation</h2>
1505
1506<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1507What compiler technology is used to build the compilers?</h3>
1508
1509<p>
Mike Rossetb4afe882013-03-12 17:12:56 -07001510<code>Gccgo</code> has a front end written in C++, with a recursive descent parser coupled to the
Rob Pike0c2a4792009-11-01 20:50:42 -08001511standard GCC back end. <code>Gc</code> is written in C using
1512<code>yacc</code>/<code>bison</code> for the parser.
Russ Cox32274452009-10-22 00:13:51 -07001513Although it's a new program, it fits in the Plan 9 C compiler suite
1514(<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 +08001515and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001516</p>
Russ Cox32274452009-10-22 00:13:51 -07001517
1518<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001519We considered writing <code>gc</code>, the original Go compiler, in Go itself but
Russ Cox32274452009-10-22 00:13:51 -07001520elected not to do so because of the difficulties of bootstrapping and
Rob Pike0c2a4792009-11-01 20:50:42 -08001521especially of open source distribution&mdash;you'd need a Go compiler to
1522set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
Rob Pike48ecfc92013-03-27 15:26:57 -07001523consider writing a compiler in Go, which might well happen.
1524(Go would be a
Russ Cox32274452009-10-22 00:13:51 -07001525fine language in which to implement a compiler; a native lexer and
Rob Pike48ecfc92013-03-27 15:26:57 -07001526parser are already available in the <a href="/pkg/go/"><code>go</code></a> package
1527and a type checker is in the works.)
Evan Shaw64d85762011-05-22 14:56:12 +10001528</p>
Russ Cox32274452009-10-22 00:13:51 -07001529
1530<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001531We also considered using LLVM for <code>gc</code> but we felt it was too large and
Russ Cox32274452009-10-22 00:13:51 -07001532slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001533</p>
Russ Cox32274452009-10-22 00:13:51 -07001534
Rob Pike966bf712011-03-01 13:54:22 -08001535<h3 id="How_is_the_run_time_support_implemented">
1536How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001537
1538<p>
Rob Pike966bf712011-03-01 13:54:22 -08001539Again due to bootstrapping issues, the run-time code is mostly in C (with a
Russ Cox32274452009-10-22 00:13:51 -07001540tiny bit of assembler) although Go is capable of implementing most of
Rob Pike966bf712011-03-01 13:54:22 -08001541it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
David Symondsbe96fa52011-07-31 12:59:58 +10001542<code>Gc</code> uses a custom library to keep the footprint under
Rob Pike0c2a4792009-11-01 20:50:42 -08001543control; it is
1544compiled with a version of the Plan 9 C compiler that supports
1545segmented stacks for goroutines.
Ian Lance Taylorebc40072012-02-17 05:59:15 -08001546The <code>gccgo</code> compiler implements segmented
1547stacks on Linux only, supported by recent modifications to the gold linker.
Evan Shaw64d85762011-05-22 14:56:12 +10001548</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001549
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001550<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1551Why is my trivial program such a large binary?</h3>
1552
1553<p>
Rob Pike86494442011-11-08 16:26:03 -08001554The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>)
1555do static linking. All Go binaries therefore include the Go
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001556run-time, along with the run-time type information necessary to support dynamic
1557type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001558</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001559
1560<p>
Rob Pike0130a312012-03-07 15:29:26 +11001561A simple C "hello, world" program compiled and linked statically using gcc
1562on Linux is around 750 kB,
1563including an implementation of <code>printf</code>.
1564An equivalent Go program using <code>fmt.Printf</code>
1565is around 1.2 MB, but
Rob Pike5cff1902012-02-20 12:42:50 +11001566that includes more powerful run-time support.
Evan Shaw64d85762011-05-22 14:56:12 +10001567</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001568
Rob Pike7d87f3d2011-08-06 11:21:59 +10001569<h3 id="unused_variables_and_imports">
1570Can I stop these complaints about my unused variable/import?</h3>
1571
1572<p>
1573The presence of an unused variable may indicate a bug, while
1574unused imports just slow down compilation.
1575Accumulate enough unused imports in your code tree and
1576things can get very slow.
1577For these reasons, Go allows neither.
1578</p>
1579
1580<p>
1581When developing code, it's common to create these situations
1582temporarily and it can be annoying to have to edit them out before the
Oling Cat018e89f2013-01-24 20:46:33 +11001583program will compile.
Rob Pike7d87f3d2011-08-06 11:21:59 +10001584</p>
1585
1586<p>
1587Some have asked for a compiler option to turn those checks off
1588or at least reduce them to warnings.
1589Such an option has not been added, though,
1590because compiler options should not affect the semantics of the
1591language and because the Go compiler does not report warnings, only
1592errors that prevent compilation.
1593</p>
1594
1595<p>
1596There are two reasons for having no warnings. First, if it's worth
1597complaining about, it's worth fixing in the code. (And if it's not
1598worth fixing, it's not worth mentioning.) Second, having the compiler
1599generate warnings encourages the implementation to warn about weak
1600cases that can make compilation noisy, masking real errors that
1601<em>should</em> be fixed.
1602</p>
1603
1604<p>
1605It's easy to address the situation, though. Use the blank identifier
1606to let unused things persist while you're developing.
1607</p>
1608
1609<pre>
1610import "unused"
1611
1612// This declaration marks the import as used by referencing an
1613// item from the package.
1614var _ = unused.Item // TODO: Delete before committing!
1615
1616func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001617 debugData := debug.Profile()
1618 _ = debugData // Used only during debugging.
1619 ....
Rob Pike7d87f3d2011-08-06 11:21:59 +10001620}
1621</pre>
1622
Andrew Gerrand08575732010-04-21 14:00:56 +10001623<h2 id="Performance">Performance</h2>
1624
1625<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1626Why does Go perform badly on benchmark X?</h3>
1627
1628<p>
1629One of Go's design goals is to approach the performance of C for comparable
Oling Cat018e89f2013-01-24 20:46:33 +11001630programs, yet on some benchmarks it does quite poorly, including several
1631in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries
1632for which versions of comparable performance are not available in Go.
Rob Pikefcfed142012-01-23 08:39:53 -08001633For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a>
1634depends on a multi-precision math package, and the C
Andrew Gerrand08575732010-04-21 14:00:56 +10001635versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
Oling Cat018e89f2013-01-24 20:46:33 +11001636written in optimized assembler).
Rob Pikefcfed142012-01-23 08:39:53 -08001637Benchmarks that depend on regular expressions
1638(<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are
Rob Pike86494442011-11-08 16:26:03 -08001639essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
Andrew Gerrand08575732010-04-21 14:00:56 +10001640mature, highly optimized regular expression libraries like PCRE.
1641</p>
1642
1643<p>
1644Benchmark games are won by extensive tuning and the Go versions of most
1645of the benchmarks need attention. If you measure comparable C
Rob Pikefcfed142012-01-23 08:39:53 -08001646and Go programs
1647(<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 +10001648languages are much closer in raw performance than this suite would
1649indicate.
1650</p>
1651
1652<p>
1653Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001654better, many libraries need major performance work, and the garbage collector
Oling Cat018e89f2013-01-24 20:46:33 +11001655isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
Rob Pikefcfed142012-01-23 08:39:53 -08001656garbage can have a huge effect.)
Andrew Gerrand08575732010-04-21 14:00:56 +10001657</p>
1658
Rob Pike93c4a242011-08-06 07:41:55 +10001659<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001660In any case, Go can often be very competitive.
1661There has been significant improvement in the performance of many programs
1662as the language and tools have developed.
1663See the blog post about
Rob Pike93c4a242011-08-06 07:41:55 +10001664<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1665Go programs</a> for an informative example.
1666
Andrew Gerrand4164d602010-09-29 16:52:22 +10001667<h2 id="change_from_c">Changes from C</h2>
1668
1669<h3 id="different_syntax">
1670Why is the syntax so different from C?</h3>
1671<p>
1672Other than declaration syntax, the differences are not major and stem
1673from two desires. First, the syntax should feel light, without too
1674many mandatory keywords, repetition, or arcana. Second, the language
1675has been designed to be easy to analyze
1676and can be parsed without a symbol table. This makes it much easier
1677to build tools such as debuggers, dependency analyzers, automated
1678documentation extractors, IDE plug-ins, and so on. C and its
1679descendants are notoriously difficult in this regard.
1680</p>
1681
1682<h3 id="declarations_backwards">
1683Why are declarations backwards?</h3>
1684<p>
1685They're only backwards if you're used to C. In C, the notion is that a
1686variable is declared like an expression denoting its type, which is a
1687nice idea, but the type and expression grammars don't mix very well and
1688the results can be confusing; consider function pointers. Go mostly
1689separates expression and type syntax and that simplifies things (using
1690prefix <code>*</code> for pointers is an exception that proves the rule). In C,
1691the declaration
1692</p>
1693<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001694 int* a, b;
Andrew Gerrand4164d602010-09-29 16:52:22 +10001695</pre>
1696<p>
1697declares <code>a</code> to be a pointer but not <code>b</code>; in Go
1698</p>
1699<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001700 var a, b *int
Andrew Gerrand4164d602010-09-29 16:52:22 +10001701</pre>
1702<p>
1703declares both to be pointers. This is clearer and more regular.
1704Also, the <code>:=</code> short declaration form argues that a full variable
1705declaration should present the same order as <code>:=</code> so
1706</p>
1707<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001708 var a uint64 = 1
Andrew Gerrand4164d602010-09-29 16:52:22 +10001709</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001710<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001711has the same effect as
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001712</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001713<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001714 a := uint64(1)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001715</pre>
1716<p>
1717Parsing is also simplified by having a distinct grammar for types that
1718is not just the expression grammar; keywords such as <code>func</code>
1719and <code>chan</code> keep things clear.
1720</p>
1721
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001722<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001723See the article about
Francisco Souza6033a482012-03-13 14:46:08 +11001724<a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
Rob Pike93c4a242011-08-06 07:41:55 +10001725for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001726</p>
1727
Andrew Gerrand4164d602010-09-29 16:52:22 +10001728<h3 id="no_pointer_arithmetic">
1729Why is there no pointer arithmetic?</h3>
1730<p>
1731Safety. Without pointer arithmetic it's possible to create a
1732language that can never derive an illegal address that succeeds
1733incorrectly. Compiler and hardware technology have advanced to the
1734point where a loop using array indices can be as efficient as a loop
1735using pointer arithmetic. Also, the lack of pointer arithmetic can
1736simplify the implementation of the garbage collector.
1737</p>
1738
1739<h3 id="inc_dec">
1740Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
1741<p>
1742Without pointer arithmetic, the convenience value of pre- and postfix
1743increment operators drops. By removing them from the expression
1744hierarchy altogether, expression syntax is simplified and the messy
1745issues around order of evaluation of <code>++</code> and <code>--</code>
1746(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
1747are eliminated as well. The simplification is
1748significant. As for postfix vs. prefix, either would work fine but
1749the postfix version is more traditional; insistence on prefix arose
1750with the STL, a library for a language whose name contains, ironically, a
1751postfix increment.
1752</p>
1753
1754<h3 id="semicolons">
1755Why are there braces but no semicolons? And why can't I put the opening
1756brace on the next line?</h3>
1757<p>
1758Go uses brace brackets for statement grouping, a syntax familiar to
1759programmers who have worked with any language in the C family.
1760Semicolons, however, are for parsers, not for people, and we wanted to
1761eliminate them as much as possible. To achieve this goal, Go borrows
1762a trick from BCPL: the semicolons that separate statements are in the
1763formal grammar but are injected automatically, without lookahead, by
1764the lexer at the end of any line that could be the end of a statement.
1765This works very well in practice but has the effect that it forces a
1766brace style. For instance, the opening brace of a function cannot
1767appear on a line by itself.
1768</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001769
Andrew Gerrand4164d602010-09-29 16:52:22 +10001770<p>
1771Some have argued that the lexer should do lookahead to permit the
1772brace to live on the next line. We disagree. Since Go code is meant
1773to be formatted automatically by
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001774<a href="/cmd/gofmt/"><code>gofmt</code></a>,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001775<i>some</i> style must be chosen. That style may differ from what
1776you've used in C or Java, but Go is a new language and
1777<code>gofmt</code>'s style is as good as any other. More
1778important&mdash;much more important&mdash;the advantages of a single,
1779programmatically mandated format for all Go programs greatly outweigh
1780any perceived disadvantages of the particular style.
1781Note too that Go's style means that an interactive implementation of
1782Go can use the standard syntax one line at a time without special rules.
1783</p>
1784
1785<h3 id="garbage_collection">
1786Why do garbage collection? Won't it be too expensive?</h3>
1787<p>
1788One of the biggest sources of bookkeeping in systems programs is
1789memory management. We feel it's critical to eliminate that
1790programmer overhead, and advances in garbage collection
1791technology in the last few years give us confidence that we can
1792implement it with low enough overhead and no significant
Rob Pikefcfed142012-01-23 08:39:53 -08001793latency.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001794</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001795
Andrew Gerrand4164d602010-09-29 16:52:22 +10001796<p>
1797Another point is that a large part of the difficulty of concurrent
1798and multi-threaded programming is memory management;
1799as objects get passed among threads it becomes cumbersome
1800to guarantee they become freed safely.
1801Automatic garbage collection makes concurrent code far easier to write.
1802Of course, implementing garbage collection in a concurrent environment is
1803itself a challenge, but meeting it once rather than in every
1804program helps everyone.
1805</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001806
Andrew Gerrand4164d602010-09-29 16:52:22 +10001807<p>
1808Finally, concurrency aside, garbage collection makes interfaces
1809simpler because they don't need to specify how memory is managed across them.
1810</p>
Rob Pike93c4a242011-08-06 07:41:55 +10001811
1812<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001813The current implementation is a parallel mark-and-sweep
1814collector but a future version might take a different approach.
1815</p>
1816
1817<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001818On the topic of performance, keep in mind that Go gives the programmer
1819considerable control over memory layout and allocation, much more than
1820is typical in garbage-collected languages. A careful programmer can reduce
1821the garbage collection overhead dramatically by using the language well;
1822see the article about
1823<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1824Go programs</a> for a worked example, including a demonstration of Go's
1825profiling tools.
1826</p>