blob: fb2d929bd69fd4ca3c5571b737692e70edf25573 [file] [log] [blame]
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11001<!--{
Andrew Gerrand5dd74172013-09-16 15:47:13 +10002 "Title": "Frequently Asked Questions (FAQ)",
Russ Cox10ea6512012-09-24 20:57:01 -04003 "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 Pike0d5bc0c2013-08-20 06:44:41 +100058<p>
59A much more expansive answer to this question is available in the article,
60<a href="http://talks.golang.org/2012/splash.article">Go at Google:
61Language Design in the Service of Software Engineering</a>.
62
Rob Pike8de50802012-07-16 13:31:15 -070063<h3 id="What_is_the_status_of_the_project">
64What is the status of the project?</h3>
65
66<p>
67Go became a public open source project on November 10, 2009.
68After a couple of years of very active design and development, stability was called for and
69Go 1 was <a href="http://blog.golang.org/2012/03/go-version-1-is-released.html">released</a>
70on March 28, 2012.
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +100071Go 1, which includes a <a href="/ref/spec">language specification</a>,
Rob Pike8de50802012-07-16 13:31:15 -070072<a href="/pkg/">standard libraries</a>,
73and <a href="/cmd/go/">custom tools</a>,
74provides a stable foundation for creating reliable products, projects, and publications.
75</p>
76
77<p>
78With that stability established, we are using Go to develop programs, products, and tools rather than
79actively changing the language and libraries.
80In fact, the purpose of Go 1 is to provide <a href="/doc/go1compat.html">long-term stability</a>.
81Backwards-incompatible changes will not be made to any Go 1 point release.
82We want to use what we have to learn how a future version of Go might look, rather than to play with
83the language underfoot.
84</p>
85
86<p>
87Of course, development will continue on Go itself, but the focus will be on performance, reliability,
88portability and the addition of new functionality such as improved support for internationalization.
89</p>
90
91<p>
92There 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.
93</p>
94
Russ Cox32274452009-10-22 00:13:51 -070095<h3 id="What_is_the_origin_of_the_name">
96What is the origin of the name?</h3>
97
98<p>
Russ Coxe434f1a2009-11-07 17:31:22 -080099&ldquo;Ogle&rdquo; would be a good name for a Go debugger.
Evan Shaw64d85762011-05-22 14:56:12 +1000100</p>
Russ Cox32274452009-10-22 00:13:51 -0700101
Rob Pikebdecae92009-11-23 17:34:23 -0800102<h3 id="Whats_the_origin_of_the_mascot">
103What's the origin of the mascot?</h3>
104
105<p>
106The mascot and logo were designed by
107<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
108<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
109the Plan 9 bunny.
110The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
111T-shirt design some years ago.
112The logo and mascot are covered by the
113<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
114license.
115</p>
116
Andrew Gerrand4164d602010-09-29 16:52:22 +1000117<h3 id="history">
118What is the history of the project?</h3>
119<p>
120Robert Griesemer, Rob Pike and Ken Thompson started sketching the
121goals for a new language on the white board on September 21, 2007.
122Within a few days the goals had settled into a plan to do something
123and a fair idea of what it would be. Design continued part-time in
124parallel with unrelated work. By January 2008, Ken had started work
125on a compiler with which to explore ideas; it generated C code as its
126output. By mid-year the language had become a full-time project and
127had settled enough to attempt a production compiler. In May 2008,
128Ian Taylor independently started on a GCC front end for Go using the
129draft specification. Russ Cox joined in late 2008 and helped move the language
130and libraries from prototype to reality.
131</p>
132
133<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000134Go became a public open source project on November 10, 2009.
135Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000136</p>
137
Andrew Gerrand4164d602010-09-29 16:52:22 +1000138<h3 id="creating_a_new_language">
139Why are you creating a new language?</h3>
140<p>
141Go was born out of frustration with existing languages and
142environments for systems programming. Programming had become too
143difficult and the choice of languages was partly to blame. One had to
144choose either efficient compilation, efficient execution, or ease of
145programming; all three were not available in the same mainstream
146language. Programmers who could were choosing ease over
147safety and efficiency by moving to dynamically typed languages such as
148Python and JavaScript rather than C++ or, to a lesser extent, Java.
149</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000150
Andrew Gerrand4164d602010-09-29 16:52:22 +1000151<p>
152Go is an attempt to combine the ease of programming of an interpreted,
153dynamically typed
154language with the efficiency and safety of a statically typed, compiled language.
155It also aims to be modern, with support for networked and multicore
156computing. Finally, it is intended to be <i>fast</i>: it should take
157at most a few seconds to build a large executable on a single computer.
158To meet these goals required addressing a number of
159linguistic issues: an expressive but lightweight type system;
160concurrency and garbage collection; rigid dependency specification;
161and so on. These cannot be addressed well by libraries or tools; a new
162language was called for.
163</p>
164
Rob Pike48ecfc92013-03-27 15:26:57 -0700165<p>
166The article <a href="http://talks.golang.org/2012/splash.article">Go at Google</a>
167discusses the background and motivation behind the design of the Go language,
168as well as providing more detail about many of the answers presented in this FAQ.
169</p>
170
Andrew Gerrand4164d602010-09-29 16:52:22 +1000171<h3 id="ancestors">
172What are Go's ancestors?</h3>
173<p>
174Go is mostly in the C family (basic syntax),
175with significant input from the Pascal/Modula/Oberon
176family (declarations, packages),
177plus some ideas from languages
178inspired by Tony Hoare's CSP,
179such as Newsqueak and Limbo (concurrency).
180However, it is a new language across the board.
181In every respect the language was designed by thinking
182about what programmers do and how to make programming, at least the
183kind of programming we do, more effective, which means more fun.
184</p>
185
Andrew Gerrand4164d602010-09-29 16:52:22 +1000186<h3 id="principles">
187What are the guiding principles in the design?</h3>
188<p>
189Programming today involves too much bookkeeping, repetition, and
190clerical work. As Dick Gabriel says, &ldquo;Old programs read
191like quiet conversations between a well-spoken research worker and a
192well-studied mechanical colleague, not as a debate with a compiler.
193Who'd have guessed sophistication bought such noise?&rdquo;
194The sophistication is worthwhile&mdash;no one wants to go back to
195the old languages&mdash;but can it be more quietly achieved?
196</p>
197<p>
198Go attempts to reduce the amount of typing in both senses of the word.
199Throughout its design, we have tried to reduce clutter and
200complexity. There are no forward declarations and no header files;
201everything is declared exactly once. Initialization is expressive,
202automatic, and easy to use. Syntax is clean and light on keywords.
203Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
204simple type derivation using the <code>:=</code>
205declare-and-initialize construct. And perhaps most radically, there
206is no type hierarchy: types just <i>are</i>, they don't have to
207announce their relationships. These simplifications allow Go to be
208expressive yet comprehensible without sacrificing, well, sophistication.
209</p>
210<p>
211Another important principle is to keep the concepts orthogonal.
212Methods can be implemented for any type; structures represent data while
213interfaces represent abstraction; and so on. Orthogonality makes it
214easier to understand what happens when things combine.
215</p>
216
Russ Cox32274452009-10-22 00:13:51 -0700217<h2 id="Usage">Usage</h2>
218
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000219<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800220
Evan Shaw64d85762011-05-22 14:56:12 +1000221<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100222Yes. There are now several Go programs deployed in
Rob Pikefcfed142012-01-23 08:39:53 -0800223production inside Google. A public example is the server behind
224<a href="http://golang.org">http://golang.org</a>.
225It's just the <a href="/cmd/godoc"><code>godoc</code></a>
226document server running in a production configuration on
Dave Cheney82cbcb02012-07-11 09:41:08 -0700227<a href="https://developers.google.com/appengine/">Google App Engine</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000228</p>
Rob Pike7685a672009-11-09 20:25:45 -0800229
Rob Pike48ecfc92013-03-27 15:26:57 -0700230<p>
231Other examples include the <a href="https://code.google.com/p/vitess/">Vitess</a>
232system for large-scale SQL installations and Google's download server, <code>dl.google.com</code>,
233which delivers Chrome binaries and other large installables such as <code>apt-get</code>
234packages.
235</p>
236
Russ Cox32274452009-10-22 00:13:51 -0700237<h3 id="Do_Go_programs_link_with_Cpp_programs">
238Do Go programs link with C/C++ programs?</h3>
239
240<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +1100241There are two Go compiler implementations, <code>gc</code>
242(the <code>6g</code> program and friends) and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800243<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700244therefore only be linked with C programs using the same convention.
Oling Cat018e89f2013-01-24 20:46:33 +1100245There is such a C compiler but no C++ compiler.
246<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
247GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000248</p>
Russ Cox32274452009-10-22 00:13:51 -0700249
250<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100251The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
252&ldquo;foreign function interface&rdquo; to allow safe calling of
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000253C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000254</p>
255
Russ Cox32274452009-10-22 00:13:51 -0700256
Rob Pike0c2a4792009-11-01 20:50:42 -0800257<h3 id="Does_Go_support_Google_protocol_buffers">
258Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700259
260<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700261A separate open source project provides the necessary compiler plugin and library.
262It is available at
263<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
264</p>
Russ Cox32274452009-10-22 00:13:51 -0700265
Evan Shaw64d85762011-05-22 14:56:12 +1000266
Russ Cox6301fb42009-12-03 17:23:33 -0800267<h3 id="Can_I_translate_the_Go_home_page">
268Can I translate the Go home page into another language?</h3>
269
270<p>
271Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000272However, if you choose to add the Google logo or branding to your site
Russ Cox6301fb42009-12-03 17:23:33 -0800273(it does not appear on <a href="http://golang.org/">golang.org</a>),
274you will need to abide by the guidelines at
275<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
276</p>
277
Russ Cox32274452009-10-22 00:13:51 -0700278<h2 id="Design">Design</h2>
279
Andrew Gerrand4164d602010-09-29 16:52:22 +1000280<h3 id="unicode_identifiers">
281What's up with Unicode identifiers?</h3>
282
283<p>
284It was important to us to extend the space of identifiers from the
285confines of ASCII. Go's rule&mdash;identifier characters must be
286letters or digits as defined by Unicode&mdash;is simple to understand
287and to implement but has restrictions. Combining characters are
288excluded by design, for instance.
289Until there
290is an agreed external definition of what an identifier might be,
291plus a definition of canonicalization of identifiers that guarantees
292no ambiguity, it seemed better to keep combining characters out of
293the mix. Thus we have a simple rule that can be expanded later
294without breaking programs, one that avoids bugs that would surely arise
295from a rule that admits ambiguous identifiers.
296</p>
297
298<p>
299On a related note, since an exported identifier must begin with an
300upper-case letter, identifiers created from &ldquo;letters&rdquo;
301in some languages can, by definition, not be exported. For now the
302only solution is to use something like <code>X日本語</code>, which
303is clearly unsatisfactory; we are considering other options. The
304case-for-visibility rule is unlikely to change however; it's one
305of our favorite features of Go.
306</p>
307
308<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700309
310<p>
311Every language contains novel features and omits someone's favorite
312feature. Go was designed with an eye on felicity of programming, speed of
313compilation, orthogonality of concepts, and the need to support features
314such as concurrency and garbage collection. Your favorite feature may be
315missing because it doesn't fit, because it affects compilation speed or
316clarity of design, or because it would make the fundamental system model
317too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000318</p>
Russ Cox32274452009-10-22 00:13:51 -0700319
320<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800321If it bothers you that Go is missing feature <var>X</var>,
322please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700323they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000324</p>
Russ Cox32274452009-10-22 00:13:51 -0700325
Andrew Gerrand4164d602010-09-29 16:52:22 +1000326<h3 id="generics">
327Why does Go not have generic types?</h3>
328<p>
329Generics may well be added at some point. We don't feel an urgency for
330them, although we understand some programmers do.
331</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000332
Andrew Gerrand4164d602010-09-29 16:52:22 +1000333<p>
334Generics are convenient but they come at a cost in
335complexity in the type system and run-time. We haven't yet found a
336design that gives value proportionate to the complexity, although we
337continue to think about it. Meanwhile, Go's built-in maps and slices,
338plus the ability to use the empty interface to construct containers
339(with explicit unboxing) mean in many cases it is possible to write
340code that does what generics would enable, if less smoothly.
341</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000342
Andrew Gerrand4164d602010-09-29 16:52:22 +1000343<p>
344This remains an open issue.
345</p>
346
347<h3 id="exceptions">
348Why does Go not have exceptions?</h3>
349<p>
350We believe that coupling exceptions to a control
351structure, as in the <code>try-catch-finally</code> idiom, results in
352convoluted code. It also tends to encourage programmers to label
353too many ordinary errors, such as failing to open a file, as
354exceptional.
355</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000356
Andrew Gerrand4164d602010-09-29 16:52:22 +1000357<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000358Go takes a different approach. For plain error handling, Go's multi-value
359returns make it easy to report an error without overloading the return value.
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100360<a href="/doc/articles/error_handling.html">A canonical error type, coupled
361with Go's other features</a>, makes error handling pleasant but quite different
362from that in other languages.
Rob Pike93c4a242011-08-06 07:41:55 +1000363</p>
364
365<p>
366Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000367of built-in functions to signal and recover from truly exceptional
368conditions. The recovery mechanism is executed only as part of a
369function's state being torn down after an error, which is sufficient
370to handle catastrophe but requires no extra control structures and,
371when used well, can result in clean error-handling code.
372</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000373
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000374<p>
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100375See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000376</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000377
Andrew Gerrand4164d602010-09-29 16:52:22 +1000378<h3 id="assertions">
379Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700380
381<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000382Go doesn't provide assertions. They are undeniably convenient, but our
383experience has been that programmers use them as a crutch to avoid thinking
384about proper error handling and reporting. Proper error handling means that
385servers continue operation after non-fatal errors instead of crashing.
386Proper error reporting means that errors are direct and to the point,
387saving the programmer from interpreting a large crash trace. Precise
388errors are particularly important when the programmer seeing the errors is
389not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000390</p>
Russ Cox32274452009-10-22 00:13:51 -0700391
Andrew Gerrand4164d602010-09-29 16:52:22 +1000392<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000393We understand that this is a point of contention. There are many things in
394the Go language and libraries that differ from modern practices, simply
395because we feel it's sometimes worth trying a different approach.
Evan Shaw64d85762011-05-22 14:56:12 +1000396</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000397
398<h3 id="csp">
399Why build concurrency on the ideas of CSP?</h3>
400<p>
401Concurrency and multi-threaded programming have a reputation
Rob Pikefcfed142012-01-23 08:39:53 -0800402for difficulty. We believe this is due partly to complex
Andrew Gerrand4164d602010-09-29 16:52:22 +1000403designs such as pthreads and partly to overemphasis on low-level details
Rob Pike93c4a242011-08-06 07:41:55 +1000404such as mutexes, condition variables, and memory barriers.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000405Higher-level interfaces enable much simpler code, even if there are still
406mutexes and such under the covers.
407</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000408
Andrew Gerrand4164d602010-09-29 16:52:22 +1000409<p>
410One of the most successful models for providing high-level linguistic support
411for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
412Occam and Erlang are two well known languages that stem from CSP.
413Go's concurrency primitives derive from a different part of the family tree
414whose main contribution is the powerful notion of channels as first class objects.
Rob Pike48ecfc92013-03-27 15:26:57 -0700415Experience with several earlier languages has shown that the CSP model
416fits well into a procedural language framework.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000417</p>
418
419<h3 id="goroutines">
420Why goroutines instead of threads?</h3>
421<p>
422Goroutines are part of making concurrency easy to use. The idea, which has
423been around for a while, is to multiplex independently executing
Rob Pike93c4a242011-08-06 07:41:55 +1000424functions&mdash;coroutines&mdash;onto a set of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000425When a coroutine blocks, such as by calling a blocking system call,
426the run-time automatically moves other coroutines on the same operating
427system thread to a different, runnable thread so they won't be blocked.
428The programmer sees none of this, which is the point.
429The result, which we call goroutines, can be very cheap: unless they spend a lot of time
430in long-running system calls, they cost little more than the memory
Rob Pike93c4a242011-08-06 07:41:55 +1000431for the stack, which is just a few kilobytes.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000432</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000433
Andrew Gerrand4164d602010-09-29 16:52:22 +1000434<p>
435To make the stacks small, Go's run-time uses segmented stacks. A newly
436minted goroutine is given a few kilobytes, which is almost always enough.
437When it isn't, the run-time allocates (and frees) extension segments automatically.
438The overhead averages about three cheap instructions per function call.
439It is practical to create hundreds of thousands of goroutines in the same
440address space. If goroutines were just threads, system resources would
441run out at a much smaller number.
442</p>
443
444<h3 id="atomic_maps">
445Why are map operations not defined to be atomic?</h3>
446
447<p>
448After long discussion it was decided that the typical use of maps did not require
Ian Lance Taylor81896052013-12-12 18:48:40 -0800449safe access from multiple goroutines, and in those cases where it did, the map was
Andrew Gerrand4164d602010-09-29 16:52:22 +1000450probably part of some larger data structure or computation that was already
451synchronized. Therefore requiring that all map operations grab a mutex would slow
452down most programs and add safety to few. This was not an easy decision,
453however, since it means uncontrolled map access can crash the program.
454</p>
455
456<p>
457The language does not preclude atomic map updates. When required, such
458as when hosting an untrusted program, the implementation could interlock
459map access.
460</p>
461
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700462<h3 id="language_changes">
463Will you accept my language change?</h3>
464
465<p>
466People often suggest improvements to the language—the
467<a href="http://groups.google.com/group/golang-nuts">mailing list</a>
468contains a rich history of such discussions—but very few of these changes have
469been accepted.
470</p>
471
472<p>
473Although Go is an open source project, the language and libraries are protected
474by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents
475changes that break existing programs.
476If your proposal violates the Go 1 specification we cannot even entertain the
477idea, regardless of its merit.
478A future major release of Go may be incompatible with Go 1, but we're not ready
479to start talking about what that might be.
480</p>
481
482<p>
Rob Pike61f3fdc2013-08-25 23:50:44 +1000483Even if your proposal is compatible with the Go 1 spec, it might
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700484not be in the spirit of Go's design goals.
485The article <i><a href="http://talks.golang.org/2012/splash.article">Go
486at Google: Language Design in the Service of Software Engineering</a></i>
487explains Go's origins and the motivation behind its design.
488</p>
489
Andrew Gerrand4164d602010-09-29 16:52:22 +1000490<h2 id="types">Types</h2>
Russ Cox32274452009-10-22 00:13:51 -0700491
492<h3 id="Is_Go_an_object-oriented_language">
493Is Go an object-oriented language?</h3>
494
495<p>
496Yes and no. Although Go has types and methods and allows an
497object-oriented style of programming, there is no type hierarchy.
Russ Coxe434f1a2009-11-07 17:31:22 -0800498The concept of &ldquo;interface&rdquo; in Go provides a different approach that
Russ Cox32274452009-10-22 00:13:51 -0700499we believe is easy to use and in some ways more general. There are
500also ways to embed types in other types to provide something
501analogous&mdash;but not identical&mdash;to subclassing.
Rob Pike0c2a4792009-11-01 20:50:42 -0800502Moreover, methods in Go are more general than in C++ or Java:
Rob Pikefcfed142012-01-23 08:39:53 -0800503they can be defined for any sort of data, even built-in types such
504as plain, &ldquo;unboxed&rdquo; integers.
505They are not restricted to structs (classes).
Evan Shaw64d85762011-05-22 14:56:12 +1000506</p>
Russ Cox32274452009-10-22 00:13:51 -0700507
508<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800509Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800510lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000511</p>
Russ Cox32274452009-10-22 00:13:51 -0700512
513<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
514How do I get dynamic dispatch of methods?</h3>
515
516<p>
517The only way to have dynamically dispatched methods is through an
Rob Pikefcfed142012-01-23 08:39:53 -0800518interface. Methods on a struct or any other concrete type are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000519</p>
Russ Cox32274452009-10-22 00:13:51 -0700520
Andrew Gerrand4164d602010-09-29 16:52:22 +1000521<h3 id="inheritance">
522Why is there no type inheritance?</h3>
523<p>
524Object-oriented programming, at least in the best-known languages,
525involves too much discussion of the relationships between types,
526relationships that often could be derived automatically. Go takes a
527different approach.
528</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000529
Andrew Gerrand4164d602010-09-29 16:52:22 +1000530<p>
531Rather than requiring the programmer to declare ahead of time that two
532types are related, in Go a type automatically satisfies any interface
533that specifies a subset of its methods. Besides reducing the
534bookkeeping, this approach has real advantages. Types can satisfy
535many interfaces at once, without the complexities of traditional
536multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000537Interfaces can be very lightweight&mdash;an interface with
538one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000539Interfaces can be added after the fact if a new idea comes along
540or for testing&mdash;without annotating the original types.
541Because there are no explicit relationships between types
542and interfaces, there is no type hierarchy to manage or discuss.
543</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000544
Andrew Gerrand4164d602010-09-29 16:52:22 +1000545<p>
546It's possible to use these ideas to construct something analogous to
547type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
548enables formatted printing to any output, not just a file, or how the
549<code>bufio</code> package can be completely separate from file I/O,
Rob Pike86494442011-11-08 16:26:03 -0800550or how the <code>image</code> packages generate compressed
551image files. All these ideas stem from a single interface
Andrew Gerrand4164d602010-09-29 16:52:22 +1000552(<code>io.Writer</code>) representing a single method
553(<code>Write</code>). And that's only scratching the surface.
Rob Pike5cff1902012-02-20 12:42:50 +1100554Go's interfaces have a profound influence on how programs are structured.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000555</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000556
Andrew Gerrand4164d602010-09-29 16:52:22 +1000557<p>
558It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000559dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000560</p>
561
562<h3 id="methods_on_basics">
563Why is <code>len</code> a function and not a method?</h3>
564<p>
565We debated this issue but decided
566implementing <code>len</code> and friends as functions was fine in practice and
567didn't complicate questions about the interface (in the Go type sense)
568of basic types.
569</p>
570
571<h3 id="overloading">
572Why does Go not support overloading of methods and operators?</h3>
573<p>
574Method dispatch is simplified if it doesn't need to do type matching as well.
575Experience with other languages told us that having a variety of
576methods with the same name but different signatures was occasionally useful
577but that it could also be confusing and fragile in practice. Matching only by name
578and requiring consistency in the types was a major simplifying decision
579in Go's type system.
580</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000581
Andrew Gerrand4164d602010-09-29 16:52:22 +1000582<p>
583Regarding operator overloading, it seems more a convenience than an absolute
584requirement. Again, things are simpler without it.
585</p>
586
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100587<h3 id="implements_interface">
588Why doesn't Go have "implements" declarations?</h3>
589
590<p>
591A Go type satisfies an interface by implementing the methods of that interface,
592nothing more. This property allows interfaces to be defined and used without
Rob Pike4be9b832012-09-07 14:01:02 -0700593having to modify existing code. It enables a kind of structural typing that
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100594promotes separation of concerns and improves code re-use, and makes it easier
595to build on patterns that emerge as the code develops.
596The semantics of interfaces is one of the main reasons for Go's nimble,
597lightweight feel.
598</p>
599
600<p>
601See the <a href="#inheritance">question on type inheritance</a> for more detail.
602</p>
603
604<h3 id="guarantee_satisfies_interface">
605How can I guarantee my type satisfies an interface?</h3>
606
607<p>
608You can ask the compiler to check that the type <code>T</code> implements the
609interface <code>I</code> by attempting an assignment:
610</p>
611
612<pre>
613type T struct{}
Rob Pikefcfed142012-01-23 08:39:53 -0800614var _ I = T{} // Verify that T implements I.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100615</pre>
616
617<p>
618If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
619at compile time.
620</p>
621
622<p>
623If you wish the users of an interface to explicitly declare that they implement
624it, you can add a method with a descriptive name to the interface's method set.
625For example:
626</p>
627
628<pre>
629type Fooer interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800630 Foo()
631 ImplementsFooer()
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100632}
633</pre>
634
635<p>
636A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100637<code>Fooer</code>, clearly documenting the fact and announcing it in
638<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100639</p>
640
641<pre>
642type Bar struct{}
643func (b Bar) ImplementsFooer() {}
644func (b Bar) Foo() {}
645</pre>
646
647<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100648Most code doesn't make use of such constraints, since they limit the utility of
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100649the interface idea. Sometimes, though, they're necessary to resolve ambiguities
650among similar interfaces.
651</p>
652
Rob Pike93c4a242011-08-06 07:41:55 +1000653<h3 id="t_and_equal_interface">
654Why doesn't type T satisfy the Equal interface?</h3>
655
656<p>
657Consider this simple interface to represent an object that can compare
658itself with another value:
659</p>
660
661<pre>
662type Equaler interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800663 Equal(Equaler) bool
Rob Pike93c4a242011-08-06 07:41:55 +1000664}
665</pre>
666
667<p>
668and this type, <code>T</code>:
669</p>
670
671<pre>
672type T int
673func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
674</pre>
675
676<p>
677Unlike the analogous situation in some polymorphic type systems,
678<code>T</code> does not implement <code>Equaler</code>.
679The argument type of <code>T.Equal</code> is <code>T</code>,
680not literally the required type <code>Equaler</code>.
681</p>
682
683<p>
684In Go, the type system does not promote the argument of
685<code>Equal</code>; that is the programmer's responsibility, as
686illustrated by the type <code>T2</code>, which does implement
687<code>Equaler</code>:
688</p>
689
690<pre>
691type T2 int
692func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
693</pre>
694
695<p>
696Even this isn't like other type systems, though, because in Go <em>any</em>
697type that satisfies <code>Equaler</code> could be passed as the
698argument to <code>T2.Equal</code>, and at run time we must
699check that the argument is of type <code>T2</code>.
700Some languages arrange to make that guarantee at compile time.
701</p>
702
703<p>
704A related example goes the other way:
705</p>
706
707<pre>
708type Opener interface {
David Symondsc9121502013-05-22 12:28:58 +1000709 Open() Reader
Rob Pike93c4a242011-08-06 07:41:55 +1000710}
711
712func (t T3) Open() *os.File
713</pre>
714
715<p>
716In Go, <code>T3</code> does not satisfy <code>Opener</code>,
717although it might in another language.
718</p>
719
720<p>
721While it is true that Go's type system does less for the programmer
722in such cases, the lack of subtyping makes the rules about
723interface satisfaction very easy to state: are the function's names
724and signatures exactly those of the interface?
725Go's rule is also easy to implement efficiently.
726We feel these benefits offset the lack of
727automatic type promotion. Should Go one day adopt some form of generic
728typing, we expect there would be a way to express the idea of these
729examples and also have them be statically checked.
730</p>
731
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000732<h3 id="convert_slice_of_interface">
733Can I convert a []T to an []interface{}?</h3>
734
735<p>
Rob Pike86494442011-11-08 16:26:03 -0800736Not directly, because they do not have the same representation in memory.
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000737It is necessary to copy the elements individually to the destination
738slice. This example converts a slice of <code>int</code> to a slice of
739<code>interface{}</code>:
740</p>
741
742<pre>
743t := []int{1, 2, 3, 4}
744s := make([]interface{}, len(t))
745for i, v := range t {
Rob Pikefcfed142012-01-23 08:39:53 -0800746 s[i] = v
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000747}
748</pre>
749
Rob Pike1e0f97a2012-02-17 16:27:17 +1100750<h3 id="nil_error">
751Why is my nil error value not equal to nil?
752</h3>
753
754<p>
755Under the covers, interfaces are implemented as two elements, a type and a value.
756The value, called the interface's dynamic value,
757is an arbitrary concrete value and the type is that of the value.
758For the <code>int</code> value 3, an interface value contains,
759schematically, (<code>int</code>, <code>3</code>).
760</p>
761
762<p>
763An interface value is <code>nil</code> only if the inner value and type are both unset,
764(<code>nil</code>, <code>nil</code>).
765In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
766If we store a pointer of type <code>*int</code> inside
767an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
768(<code>*int</code>, <code>nil</code>).
769Such an interface value will therefore be non-<code>nil</code>
770<em>even when the pointer inside is</em> <code>nil</code>.
771</p>
772
773<p>
774This situation can be confusing, and often arises when a <code>nil</code> value is
775stored inside an interface value such as an <code>error</code> return:
776</p>
777
778<pre>
779func returnsError() error {
780 var p *MyError = nil
781 if bad() {
782 p = ErrBad
783 }
784 return p // Will always return a non-nil error.
785}
786</pre>
787
788<p>
789If all goes well, the function returns a <code>nil</code> <code>p</code>,
790so the return value is an <code>error</code> interface
791value holding (<code>*MyError</code>, <code>nil</code>).
792This means that if the caller compares the returned error to <code>nil</code>,
793it will always look as if there was an error even if nothing bad happened.
794To return a proper <code>nil</code> <code>error</code> to the caller,
795the function must return an explicit <code>nil</code>:
796</p>
797
798
799<pre>
800func returnsError() error {
801 if bad() {
802 return ErrBad
803 }
804 return nil
805}
806</pre>
807
808<p>
809It's a good idea for functions
810that return errors always to use the <code>error</code> type in
811their signature (as we did above) rather than a concrete type such
812as <code>*MyError</code>, to help guarantee the error is
813created correctly. As an example,
814<a href="/pkg/os/#Open"><code>os.Open</code></a>
815returns an <code>error</code> even though, if not <code>nil</code>,
816it's always of concrete type
817<a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
818</p>
819
820<p>
821Similar situations to those described here can arise whenever interfaces are used.
822Just keep in mind that if any concrete value
823has been stored in the interface, the interface will not be <code>nil</code>.
824For more information, see
Shenghou Macb6c09a2012-03-01 14:54:35 +0800825<a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
Rob Pike1e0f97a2012-02-17 16:27:17 +1100826</p>
827
828
Rob Pike7d87f3d2011-08-06 11:21:59 +1000829<h3 id="unions">
830Why are there no untagged unions, as in C?</h3>
831
832<p>
833Untagged unions would violate Go's memory safety
834guarantees.
835</p>
836
837<h3 id="variant_types">
838Why does Go not have variant types?</h3>
839
840<p>
841Variant types, also known as algebraic types, provide a way to specify
842that a value might take one of a set of other types, but only those
843types. A common example in systems programming would specify that an
844error is, say, a network error, a security error or an application
845error and allow the caller to discriminate the source of the problem
846by examining the type of the error. Another example is a syntax tree
847in which each node can be a different type: declaration, statement,
848assignment and so on.
849</p>
850
851<p>
852We considered adding variant types to Go, but after discussion
853decided to leave them out because they overlap in confusing ways
854with interfaces. What would happen if the elements of a variant type
855were themselves interfaces?
856</p>
857
858<p>
859Also, some of what variant types address is already covered by the
860language. The error example is easy to express using an interface
861value to hold the error and a type switch to discriminate cases. The
862syntax tree example is also doable, although not as elegantly.
863</p>
864
Andrew Gerrand4164d602010-09-29 16:52:22 +1000865<h2 id="values">Values</h2>
866
867<h3 id="conversions">
868Why does Go not provide implicit numeric conversions?</h3>
869<p>
870The convenience of automatic conversion between numeric types in C is
871outweighed by the confusion it causes. When is an expression unsigned?
872How big is the value? Does it overflow? Is the result portable, independent
873of the machine on which it executes?
874It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
875are not easy to implement and inconsistent across architectures.
876For reasons of portability, we decided to make things clear and straightforward
877at the cost of some explicit conversions in the code.
878The definition of constants in Go&mdash;arbitrary precision values free
879of signedness and size annotations&mdash;ameliorates matters considerably,
880though.
881</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000882
Andrew Gerrand4164d602010-09-29 16:52:22 +1000883<p>
884A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
885are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
886type is generic; if you care about how many bits an integer holds, Go
887encourages you to be explicit.
888</p>
889
890<h3 id="builtin_maps">
891Why are maps built in?</h3>
892<p>
893The same reason strings are: they are such a powerful and important data
894structure that providing one excellent implementation with syntactic support
895makes programming more pleasant. We believe that Go's implementation of maps
896is strong enough that it will serve for the vast majority of uses.
897If a specific application can benefit from a custom implementation, it's possible
898to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
899</p>
900
Andrew Gerrand4164d602010-09-29 16:52:22 +1000901<h3 id="map_keys">
Rob Pikefcfed142012-01-23 08:39:53 -0800902Why don't maps allow slices as keys?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000903<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800904Map lookup requires an equality operator, which slices do not implement.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000905They don't implement equality because equality is not well defined on such types;
906there are multiple considerations involving shallow vs. deep comparison, pointer vs.
Rob Pikefcfed142012-01-23 08:39:53 -0800907value comparison, how to deal with recursive types, and so on.
908We may revisit this issue&mdash;and implementing equality for slices
Andrew Gerrand4164d602010-09-29 16:52:22 +1000909will not invalidate any existing programs&mdash;but without a clear idea of what
Rob Pike5cff1902012-02-20 12:42:50 +1100910equality of slices should mean, it was simpler to leave it out for now.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000911</p>
912
Rob Pikefcfed142012-01-23 08:39:53 -0800913<p>
Rob Pike5cff1902012-02-20 12:42:50 +1100914In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
915types can be used as map keys. Slices still do not have a definition of equality, though.
Rob Pikefcfed142012-01-23 08:39:53 -0800916</p>
917
Andrew Gerrand4164d602010-09-29 16:52:22 +1000918<h3 id="references">
919Why are maps, slices, and channels references while arrays are values?</h3>
920<p>
921There's a lot of history on that topic. Early on, maps and channels
922were syntactically pointers and it was impossible to declare or use a
923non-pointer instance. Also, we struggled with how arrays should work.
924Eventually we decided that the strict separation of pointers and
Rob Pike48ecfc92013-03-27 15:26:57 -0700925values made the language harder to use. Changing these
926types to act as references to the associated, shared data structures resolved
927these issues. This change added some regrettable complexity to the
928language but had a large effect on usability: Go became a more
929productive, comfortable language when it was introduced.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000930</p>
931
Russ Cox32274452009-10-22 00:13:51 -0700932<h2 id="Writing_Code">Writing Code</h2>
933
934<h3 id="How_are_libraries_documented">
935How are libraries documented?</h3>
936
937<p>
938There is a program, <code>godoc</code>, written in Go, that extracts
939package documentation from the source code. It can be used on the
940command line or on the web. An instance is running at
Rob Pike0c2a4792009-11-01 20:50:42 -0800941<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -0800942In fact, <code>godoc</code> implements the full site at
Rob Pike0c2a4792009-11-01 20:50:42 -0800943<a href="http://golang.org/">http://golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000944</p>
Russ Cox32274452009-10-22 00:13:51 -0700945
946<h3 id="Is_there_a_Go_programming_style_guide">
947Is there a Go programming style guide?</h3>
948
949<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800950Eventually, there may be a small number of rules to guide things
951like naming, layout, and file organization.
952The document <a href="effective_go.html">Effective Go</a>
953contains some style advice.
954More directly, the program <code>gofmt</code> is a pretty-printer
955whose purpose is to enforce layout rules; it replaces the usual
956compendium of do's and don'ts that allows interpretation.
957All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +1000958</p>
Russ Cox32274452009-10-22 00:13:51 -0700959
Rob Pike3a7fe362014-03-06 13:15:09 +1100960<p>
961The document titled
962<a href="http://golang.org/s/comments">Go Code Review Comments</a>
963is a collection of very short essays about details of Go idiom that are often
964missed by programmers.
965It is a handy reference for people doing code reviews for Go projects.
966</p>
967
Russ Cox32274452009-10-22 00:13:51 -0700968<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
969How do I submit patches to the Go libraries?</h3>
970
Rob Pike0c2a4792009-11-01 20:50:42 -0800971<p>
972The library sources are in <code>go/src/pkg</code>.
973If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +1000974</p>
Russ Cox32274452009-10-22 00:13:51 -0700975
Rob Pike0c2a4792009-11-01 20:50:42 -0800976<p>
977See the document
978<a href="contribute.html">Contributing to the Go project</a>
979for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +1000980</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000981
Rob Pike91f2a342012-09-07 11:19:01 -0700982<h3 id="Why_does_the_project_use_Mercurial_and_not_git">
983Why does the project use Mercurial and not git?</h3>
984
985<p>
986The Go project, hosted by Google Code at
987<a href="http://code.google.com/p/go">code.google.com/p/go</a>,
988uses Mercurial as its version control system.
989When the project launched,
990Google Code supported only Subversion and Mercurial.
991Mercurial was a better choice because of its plugin mechanism
992that allowed us to create the "codereview" plugin to connect
Oling Cat018e89f2013-01-24 20:46:33 +1100993the project to the excellent code review tools at
Rob Pike91f2a342012-09-07 11:19:01 -0700994<a href="http://codereview.appspot.com">codereview.appspot.com</a>.
995</p>
996
997<p>
998Programmers who work
999with the Go project's source rather than release downloads sometimes
1000ask for the project to switch to git.
1001That would be possible, but it would be a lot of work and
1002would also require reimplementing the codereview plugin.
1003Given that Mercurial works today, with code review support,
1004combined with the Go project's mostly linear, non-branching use of
1005version control, a switch to git doesn't seem worthwhile.
1006</p>
1007
Herbert Georg Fischer99021b72013-03-15 13:43:10 -07001008<h3 id="git_https">
1009Why does "go get" use HTTPS when cloning a repository?</h3>
1010
1011<p>
1012Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
1013and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418
1014(git) and TCP port 22 (SSH).
1015When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
1016default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
1017The <code>go get</code> command therefore uses HTTPS for safety.
1018</p>
1019
1020<p>
1021If you use <code>git</code> and prefer to push changes through SSH using your existing key
1022it's easy to work around this. For GitHub, try one of these solutions:
1023</p>
1024<ul>
1025<li>Manually clone the repository in the expected package directory:
1026<pre>
1027$ cd $GOPATH/src/github.com/username
1028$ git clone git@github.com:username/package.git
1029</pre>
1030</li>
1031<li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending
1032these two lines to <code>~/.gitconfig</code>:
1033<pre>
1034[url "git@github.com:"]
1035 pushInsteadOf = https://github.com/
1036</pre>
1037</li>
1038</ul>
1039
Russ Coxdc8d9032013-10-03 09:18:47 -04001040<h3 id="get_version">
1041How should I manage package versions using "go get"?</h3>
1042
1043<p>
1044"Go get" does not have any explicit concept of package versions.
1045Versioning is a source of significant complexity, especially in large code bases,
1046and we are unaware of any approach that works well at scale in a large enough
1047variety of situations to be appropriate to force on all Go users.
1048What "go get" and the larger Go toolchain do provide is isolation of
1049packages with different import paths.
1050For example, the standard library's <code>html/template</code> and <code>text/template</code>
1051coexist even though both are "package template".
1052This observation leads to some advice for package authors and package users.
1053</p>
1054
1055<p>
1056Packages intended for public use should try to maintain backwards compatibility as they evolve.
1057The <a href="/doc/go1compat.html">Go 1 compatibility guidelines</a> are a good reference here:
1058don't remove exported names, encourage tagged composite literals, and so on.
1059If different functionality is required, add a new name instead of changing an old one.
1060If a complete break is required, create a new package with a new import path.</p>
1061
1062<p>
1063If you're using an externally supplied package and worry that it might change in
1064unexpected ways, the simplest solution is to copy it to your local repository.
1065(This is the approach Google takes internally.)
1066Store the copy under a new import path that identifies it as a local copy.
1067For example, you might copy "original.com/pkg" to "you.com/external/original.com/pkg".
1068Keith Rarick's <a href="https://github.com/kr/goven">goven</a> is one tool to help automate this process.
1069</p>
1070
Andrew Gerrand4164d602010-09-29 16:52:22 +10001071<h2 id="Pointers">Pointers and Allocation</h2>
1072
1073<h3 id="pass_by_value">
1074When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001075
1076<p>
Rob Pike86494442011-11-08 16:26:03 -08001077As in all languages in the C family, everything in Go is passed by value.
1078That is, a function always gets a copy of the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001079thing being passed, as if there were an assignment statement assigning the
Rob Pike86494442011-11-08 16:26:03 -08001080value to the parameter. For instance, passing an <code>int</code> value
1081to a function makes a copy of the <code>int</code>, and passing a pointer
1082value makes a copy of the pointer, but not the data it points to.
1083(See the next section for a discussion of how this affects method receivers.)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001084</p>
Russ Cox32274452009-10-22 00:13:51 -07001085
1086<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001087Map and slice values behave like pointers: they are descriptors that
Andrew Gerrand4164d602010-09-29 16:52:22 +10001088contain pointers to the underlying map or slice data. Copying a map or
1089slice value doesn't copy the data it points to. Copying an interface value
1090makes a copy of the thing stored in the interface value. If the interface
1091value holds a struct, copying the interface value makes a copy of the
1092struct. If the interface value holds a pointer, copying the interface value
Oling Cat018e89f2013-01-24 20:46:33 +11001093makes a copy of the pointer, but again not the data it points to.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001094</p>
1095
Rob Pike09cd13c2013-03-15 11:38:50 -07001096<h3 id="pointer_to_interface">
1097When should I use a pointer to an interface?</h3>
1098
1099<p>
1100Almost never. Pointers to interface values arise only in rare, tricky situations involving
1101disguising an interface value's type for delayed evaluation.
1102</p>
1103
1104<p>
1105It is however a common mistake to pass a pointer to an interface value
1106to a function expecting an interface. The compiler will complain about this
1107error but the situation can still be confusing, because sometimes a
1108<a href="#different_method_sets">pointer
1109is necessary to satisfy an interface</a>.
1110The insight is that although a pointer to a concrete type can satisfy
1111an interface, with one exception <em>a pointer to an interface can never satisfy a interface</em>.
1112</p>
1113
1114<p>
1115Consider the variable declaration,
1116</p>
1117
1118<pre>
1119var w io.Writer
1120</pre>
1121
1122<p>
1123The printing function <code>fmt.Fprintf</code> takes as its first argument
1124a value that satisfies <code>io.Writer</code>—something that implements
1125the canonical <code>Write</code> method. Thus we can write
1126</p>
1127
1128<pre>
1129fmt.Fprintf(w, "hello, world\n")
1130</pre>
1131
1132<p>
1133If however we pass the address of <code>w</code>, the program will not compile.
1134</p>
1135
1136<pre>
1137fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
1138</pre>
1139
1140<p>
1141The one exception is that any value, even a pointer to an interface, can be assigned to
1142a variable of empty interface type (<code>interface{}</code>).
1143Even so, it's almost certainly a mistake if the value is a pointer to an interface;
1144the result can be confusing.
1145</p>
1146
Andrew Gerrand4164d602010-09-29 16:52:22 +10001147<h3 id="methods_on_values_or_pointers">
1148Should I define methods on values or pointers?</h3>
1149
1150<pre>
Rob Pike93c4a242011-08-06 07:41:55 +10001151func (s *MyStruct) pointerMethod() { } // method on pointer
1152func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +10001153</pre>
Russ Cox32274452009-10-22 00:13:51 -07001154
1155<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001156For programmers unaccustomed to pointers, the distinction between these
1157two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001158When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike5cff1902012-02-20 12:42:50 +11001159examples) behaves exactly as if it were an argument to the method.
Rob Pike93c4a242011-08-06 07:41:55 +10001160Whether to define the receiver as a value or as a pointer is the same
1161question, then, as whether a function argument should be a value or
1162a pointer.
1163There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001164</p>
1165
Rob Pike93c4a242011-08-06 07:41:55 +10001166<p>
1167First, and most important, does the method need to modify the
1168receiver?
1169If it does, the receiver <em>must</em> be a pointer.
Rob Pike48ecfc92013-03-27 15:26:57 -07001170(Slices and maps act as references, so their story is a little
Rob Pike93c4a242011-08-06 07:41:55 +10001171more subtle, but for instance to change the length of a slice
1172in a method the receiver must still be a pointer.)
1173In the examples above, if <code>pointerMethod</code> modifies
1174the fields of <code>s</code>,
1175the caller will see those changes, but <code>valueMethod</code>
1176is called with a copy of the caller's argument (that's the definition
1177of passing a value), so changes it makes will be invisible to the caller.
1178</p>
1179
1180<p>
1181By the way, pointer receivers are identical to the situation in Java,
1182although in Java the pointers are hidden under the covers; it's Go's
1183value receivers that are unusual.
1184</p>
1185
1186<p>
1187Second is the consideration of efficiency. If the receiver is large,
1188a big <code>struct</code> for instance, it will be much cheaper to
1189use a pointer receiver.
1190</p>
1191
1192<p>
1193Next is consistency. If some of the methods of the type must have
1194pointer receivers, the rest should too, so the method set is
1195consistent regardless of how the type is used.
1196See the section on <a href="#different_method_sets">method sets</a>
1197for details.
1198</p>
1199
1200<p>
1201For types such as basic types, slices, and small <code>structs</code>,
1202a value receiver is very cheap so unless the semantics of the method
1203requires a pointer, a value receiver is efficient and clear.
1204</p>
1205
1206
Andrew Gerrand4164d602010-09-29 16:52:22 +10001207<h3 id="new_and_make">
1208What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001209
1210<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001211In short: <code>new</code> allocates memory, <code>make</code> initializes
1212the slice, map, and channel types.
1213</p>
1214
1215<p>
1216See the <a href="/doc/effective_go.html#allocation_new">relevant section
1217of Effective Go</a> for more details.
1218</p>
1219
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +11001220<h3 id="q_int_sizes">
Rob Pike48ecfc92013-03-27 15:26:57 -07001221What is the size of an <code>int</code> on a 64 bit machine?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001222
1223<p>
Rob Pike80e25fc2011-01-19 23:07:38 -05001224The sizes of <code>int</code> and <code>uint</code> are implementation-specific
1225but the same as each other on a given platform.
Russ Cox10ea6512012-09-24 20:57:01 -04001226For portability, code that relies on a particular
Rob Pike80e25fc2011-01-19 23:07:38 -05001227size of value should use an explicitly sized type, like <code>int64</code>.
Russ Cox10ea6512012-09-24 20:57:01 -04001228Prior to Go 1.1, the 64-bit Go compilers (both gc and gccgo) used
1229a 32-bit representation for <code>int</code>. As of Go 1.1 they use
1230a 64-bit representation.
Rob Pike80e25fc2011-01-19 23:07:38 -05001231On the other hand, floating-point scalars and complex
1232numbers are always sized: <code>float32</code>, <code>complex64</code>,
1233etc., because programmers should be aware of precision when using
1234floating-point numbers.
1235The default size of a floating-point constant is <code>float64</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001236</p>
1237
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001238<h3 id="stack_or_heap">
1239How do I know whether a variable is allocated on the heap or the stack?</h3>
1240
1241<p>
1242From a correctness standpoint, you don't need to know.
1243Each variable in Go exists as long as there are references to it.
1244The storage location chosen by the implementation is irrelevant to the
1245semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +10001246</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001247
1248<p>
1249The storage location does have an effect on writing efficient programs.
1250When possible, the Go compilers will allocate variables that are
1251local to a function in that function's stack frame. However, if the
1252compiler cannot prove that the variable is not referenced after the
1253function returns, then the compiler must allocate the variable on the
1254garbage-collected heap to avoid dangling pointer errors.
Rob Pikefcfed142012-01-23 08:39:53 -08001255Also, if a local variable is very large, it might make more sense
1256to store it on the heap rather than the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001257</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001258
1259<p>
Rob Pike86494442011-11-08 16:26:03 -08001260In the current compilers, if a variable has its address taken, that variable
1261is a candidate for allocation on the heap. However, a basic <em>escape
1262analysis</em> recognizes some cases when such variables will not
1263live past the return from the function and can reside on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001264</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001265
Andrew Gerrand21009472012-10-11 14:21:19 +11001266<h3 id="Why_does_my_Go_process_use_so_much_virtual_memory">
1267Why does my Go process use so much virtual memory?</h3>
1268
1269<p>
1270The Go memory allocator reserves a large region of virtual memory as an arena
1271for allocations. This virtual memory is local to the specific Go process; the
1272reservation does not deprive other processes of memory.
1273</p>
1274
1275<p>
1276To find the amount of actual memory allocated to a Go process, use the Unix
1277<code>top</code> command and consult the <code>RES</code> (Linux) or
1278<code>RSIZE</code> (Mac OS X) columns.
1279<!-- TODO(adg): find out how this works on Windows -->
1280</p>
1281
Andrew Gerrand4164d602010-09-29 16:52:22 +10001282<h2 id="Concurrency">Concurrency</h2>
1283
1284<h3 id="What_operations_are_atomic_What_about_mutexes">
1285What operations are atomic? What about mutexes?</h3>
1286
1287<p>
1288We haven't fully defined it all yet, but some details about atomicity are
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001289available in the <a href="/ref/mem">Go Memory Model specification</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001290</p>
1291
1292<p>
1293Regarding mutexes, the <a href="/pkg/sync">sync</a>
1294package implements them, but we hope Go programming style will
1295encourage people to try higher-level techniques. In particular, consider
1296structuring your program so that only one goroutine at a time is ever
1297responsible for a particular piece of data.
1298</p>
1299
1300<p>
1301Do not communicate by sharing memory. Instead, share memory by communicating.
1302</p>
1303
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001304<p>
1305See 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.
1306</p>
1307
Andrew Gerrand4164d602010-09-29 16:52:22 +10001308<h3 id="Why_no_multi_CPU">
1309Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1310
1311<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001312You must set the <code>GOMAXPROCS</code> shell environment variable
1313or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a>
1314of the runtime package to allow the
Oling Cat018e89f2013-01-24 20:46:33 +11001315run-time support to utilize more than one OS thread.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001316</p>
1317
1318<p>
Rob Pike86494442011-11-08 16:26:03 -08001319Programs that perform parallel computation should benefit from an increase in
Rob Pike5cff1902012-02-20 12:42:50 +11001320<code>GOMAXPROCS</code>.
Rob Pike48ecfc92013-03-27 15:26:57 -07001321However, be aware that
1322<a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">concurrency
1323is not parallelism</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001324</p>
1325
1326<h3 id="Why_GOMAXPROCS">
1327Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
1328slower?</h3>
1329
1330<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001331It depends on the nature of your program.
Rob Pike01afb792012-01-26 14:44:38 -08001332Problems that are intrinsically sequential cannot be sped up by adding
1333more goroutines.
1334Concurrency only becomes parallelism when the problem is
1335intrinsically parallel.
1336</p>
1337
1338<p>
1339In practical terms, programs that spend more time
1340communicating on channels than doing computation
1341will experience performance degradation when using
1342multiple OS threads.
1343This is because sending data between threads involves switching
1344contexts, which has significant cost.
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001345For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
Rob Pike01afb792012-01-26 14:44:38 -08001346from the Go specification has no significant parallelism although it launches many
1347goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than
1348to speed it up.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001349</p>
1350
1351<p>
Rob Pike966bf712011-03-01 13:54:22 -08001352Go's goroutine scheduler is not as good as it needs to be. In future, it
1353should recognize such cases and optimize its use of OS threads. For now,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001354<code>GOMAXPROCS</code> should be set on a per-application basis.
1355</p>
1356
Rob Pike48ecfc92013-03-27 15:26:57 -07001357<p>
1358For more detail on this topic see the talk entitled,
1359<a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency
1360is not Parallelism</a>.
1361
Andrew Gerrand4164d602010-09-29 16:52:22 +10001362<h2 id="Functions_methods">Functions and Methods</h2>
1363
1364<h3 id="different_method_sets">
1365Why do T and *T have different method sets?</h3>
1366
1367<p>
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001368From the <a href="/ref/spec#Types">Go Spec</a>:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001369</p>
1370
1371<blockquote>
1372The method set of any other named type <code>T</code> consists of all methods
1373with receiver type <code>T</code>. The method set of the corresponding pointer
1374type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1375<code>T</code> (that is, it also contains the method set of <code>T</code>).
1376</blockquote>
1377
1378<p>
1379If an interface value contains a pointer <code>*T</code>,
1380a method call can obtain a value by dereferencing the pointer,
1381but if an interface value contains a value <code>T</code>,
1382there is no useful way for a method call to obtain a pointer.
1383</p>
1384
1385<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001386Even in cases where the compiler could take the address of a value
1387to pass to the method, if the method modifies the value the changes
1388will be lost in the caller.
1389As a common example, this code:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001390</p>
1391
1392<pre>
1393var buf bytes.Buffer
1394io.Copy(buf, os.Stdin)
1395</pre>
1396
1397<p>
1398would copy standard input into a <i>copy</i> of <code>buf</code>,
1399not into <code>buf</code> itself.
1400This is almost never the desired behavior.
1401</p>
1402
1403<h3 id="closures_and_goroutines">
Rob Pikefcfed142012-01-23 08:39:53 -08001404What happens with closures running as goroutines?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001405
1406<p>
1407Some confusion may arise when using closures with concurrency.
1408Consider the following program:
1409</p>
1410
1411<pre>
1412func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001413 done := make(chan bool)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001414
Rob Pike5cff1902012-02-20 12:42:50 +11001415 values := []string{"a", "b", "c"}
Rob Pikefcfed142012-01-23 08:39:53 -08001416 for _, v := range values {
1417 go func() {
1418 fmt.Println(v)
1419 done &lt;- true
1420 }()
1421 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001422
Rob Pikefcfed142012-01-23 08:39:53 -08001423 // wait for all goroutines to complete before exiting
1424 for _ = range values {
Oling Cat018e89f2013-01-24 20:46:33 +11001425 &lt;-done
Rob Pikefcfed142012-01-23 08:39:53 -08001426 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001427}
1428</pre>
1429
1430<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001431One might mistakenly expect to see <code>a, b, c</code> as the output.
1432What you'll probably see instead is <code>c, c, c</code>. This is because
Rob Pikefcfed142012-01-23 08:39:53 -08001433each iteration of the loop uses the same instance of the variable <code>v</code>, so
Oling Cat018e89f2013-01-24 20:46:33 +11001434each closure shares that single variable. When the closure runs, it prints the
Rob Pikefcfed142012-01-23 08:39:53 -08001435value of <code>v</code> at the time <code>fmt.Println</code> is executed,
Oling Cat018e89f2013-01-24 20:46:33 +11001436but <code>v</code> may have been modified since the goroutine was launched.
Christian Himpel89ed40c2012-11-12 07:25:54 -08001437To help detect this and other problems before they happen, run
Andrew Gerrand399a36a2013-01-15 19:25:16 +11001438<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 +10001439</p>
1440
1441<p>
Rob Pike0cab7d52012-09-07 09:11:39 -07001442To bind the current value of <code>v</code> to each closure as it is launched, one
1443must modify the inner loop to create a new variable each iteration.
1444One way is to pass the variable as an argument to the closure:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001445</p>
1446
1447<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001448 for _, v := range values {
1449 go func(<b>u</b> string) {
1450 fmt.Println(<b>u</b>)
1451 done &lt;- true
1452 }(<b>v</b>)
1453 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001454</pre>
1455
1456<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001457In this example, the value of <code>v</code> is passed as an argument to the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001458anonymous function. That value is then accessible inside the function as
1459the variable <code>u</code>.
1460</p>
1461
Rob Pike0cab7d52012-09-07 09:11:39 -07001462<p>
1463Even easier is just to create a new variable, using a declaration style that may
1464seem odd but works fine in Go:
1465</p>
1466
1467<pre>
1468 for _, v := range values {
1469 <b>v := v</b> // create a new 'v'.
1470 go func() {
1471 fmt.Println(<b>v</b>)
1472 done &lt;- true
1473 }()
1474 }
1475</pre>
1476
Andrew Gerrand4164d602010-09-29 16:52:22 +10001477<h2 id="Control_flow">Control flow</h2>
1478
1479<h3 id="Does_Go_have_a_ternary_form">
1480Does Go have the <code>?:</code> operator?</h3>
1481
1482<p>
1483There is no ternary form in Go. You may use the following to achieve the same
1484result:
1485</p>
1486
1487<pre>
1488if expr {
Rob Pikefcfed142012-01-23 08:39:53 -08001489 n = trueVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001490} else {
Rob Pikefcfed142012-01-23 08:39:53 -08001491 n = falseVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001492}
1493</pre>
1494
1495<h2 id="Packages_Testing">Packages and Testing</h2>
1496
1497<h3 id="How_do_I_create_a_multifile_package">
1498How do I create a multifile package?</h3>
1499
1500<p>
1501Put all the source files for the package in a directory by themselves.
1502Source files can refer to items from different files at will; there is
1503no need for forward declarations or a header file.
1504</p>
1505
1506<p>
1507Other than being split into multiple files, the package will compile and test
1508just like a single-file package.
1509</p>
1510
1511<h3 id="How_do_I_write_a_unit_test">
1512How do I write a unit test?</h3>
1513
1514<p>
1515Create a new file ending in <code>_test.go</code> in the same directory
1516as your package sources. Inside that file, <code>import "testing"</code>
1517and write functions of the form
1518</p>
1519
1520<pre>
1521func TestFoo(t *testing.T) {
1522 ...
1523}
1524</pre>
1525
1526<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001527Run <code>go test</code> in that directory.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001528That script finds the <code>Test</code> functions,
1529builds a test binary, and runs it.
1530</p>
1531
Rob Pike5cff1902012-02-20 12:42:50 +11001532<p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
1533the <a href="/pkg/testing/"><code>testing</code></a> package
Andrew Gerrand399a36a2013-01-15 19:25:16 +11001534and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details.
Rob Pike5cff1902012-02-20 12:42:50 +11001535</p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001536
Rob Pikef6615f12011-11-09 13:19:23 -08001537<h3 id="testing_framework">
1538Where is my favorite helper function for testing?</h3>
1539
1540<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001541Go'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 -08001542features provided in other language's testing frameworks such as assertion functions.
1543An <a href="#assertions">earlier section</a> of this document explained why Go
1544doesn't have assertions, and
1545the same arguments apply to the use of <code>assert</code> in tests.
1546Proper error handling means letting other tests run after one has failed, so
1547that the person debugging the failure gets a complete picture of what is
1548wrong. It is more useful for a test to report that
1549<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
15502, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
1551answer for 2 and therefore no more tests were run. The programmer who
1552triggers the test failure may not be familiar with the code that fails.
1553Time invested writing a good error message now pays off later when the
1554test breaks.
1555</p>
1556
1557<p>
1558A related point is that testing frameworks tend to develop into mini-languages
1559of their own, with conditionals and controls and printing mechanisms,
1560but Go already has all those capabilities; why recreate them?
1561We'd rather write tests in Go; it's one fewer language to learn and the
1562approach keeps the tests straightforward and easy to understand.
1563</p>
1564
1565<p>
1566If the amount of extra code required to write
1567good errors seems repetitive and overwhelming, the test might work better if
1568table-driven, iterating over a list of inputs and outputs defined
1569in a data structure (Go has excellent support for data structure literals).
1570The work to write a good test and good error messages will then be amortized over many
1571test cases. The standard Go library is full of illustrative examples, such as in
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001572<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 -08001573</p>
1574
Russ Cox32274452009-10-22 00:13:51 -07001575
1576<h2 id="Implementation">Implementation</h2>
1577
1578<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1579What compiler technology is used to build the compilers?</h3>
1580
1581<p>
Mike Rossetb4afe882013-03-12 17:12:56 -07001582<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 -08001583standard GCC back end. <code>Gc</code> is written in C using
1584<code>yacc</code>/<code>bison</code> for the parser.
Russ Cox32274452009-10-22 00:13:51 -07001585Although it's a new program, it fits in the Plan 9 C compiler suite
1586(<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 +08001587and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001588</p>
Russ Cox32274452009-10-22 00:13:51 -07001589
1590<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001591We considered writing <code>gc</code>, the original Go compiler, in Go itself but
Russ Cox32274452009-10-22 00:13:51 -07001592elected not to do so because of the difficulties of bootstrapping and
Rob Pike0c2a4792009-11-01 20:50:42 -08001593especially of open source distribution&mdash;you'd need a Go compiler to
1594set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
Rob Pike48ecfc92013-03-27 15:26:57 -07001595consider writing a compiler in Go, which might well happen.
1596(Go would be a
Russ Cox32274452009-10-22 00:13:51 -07001597fine language in which to implement a compiler; a native lexer and
Rob Pike48ecfc92013-03-27 15:26:57 -07001598parser are already available in the <a href="/pkg/go/"><code>go</code></a> package
1599and a type checker is in the works.)
Evan Shaw64d85762011-05-22 14:56:12 +10001600</p>
Russ Cox32274452009-10-22 00:13:51 -07001601
1602<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +11001603We also considered using LLVM for <code>gc</code> but we felt it was too large and
Russ Cox32274452009-10-22 00:13:51 -07001604slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001605</p>
Russ Cox32274452009-10-22 00:13:51 -07001606
Rob Pike966bf712011-03-01 13:54:22 -08001607<h3 id="How_is_the_run_time_support_implemented">
1608How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001609
1610<p>
Rob Pike966bf712011-03-01 13:54:22 -08001611Again due to bootstrapping issues, the run-time code is mostly in C (with a
Russ Cox32274452009-10-22 00:13:51 -07001612tiny bit of assembler) although Go is capable of implementing most of
Rob Pike966bf712011-03-01 13:54:22 -08001613it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
David Symondsbe96fa52011-07-31 12:59:58 +10001614<code>Gc</code> uses a custom library to keep the footprint under
Rob Pike0c2a4792009-11-01 20:50:42 -08001615control; it is
1616compiled with a version of the Plan 9 C compiler that supports
1617segmented stacks for goroutines.
Ian Lance Taylorebc40072012-02-17 05:59:15 -08001618The <code>gccgo</code> compiler implements segmented
1619stacks on Linux only, supported by recent modifications to the gold linker.
Evan Shaw64d85762011-05-22 14:56:12 +10001620</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001621
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001622<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1623Why is my trivial program such a large binary?</h3>
1624
1625<p>
Rob Pike86494442011-11-08 16:26:03 -08001626The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>)
1627do static linking. All Go binaries therefore include the Go
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001628run-time, along with the run-time type information necessary to support dynamic
1629type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001630</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001631
1632<p>
Rob Pike0130a312012-03-07 15:29:26 +11001633A simple C "hello, world" program compiled and linked statically using gcc
1634on Linux is around 750 kB,
1635including an implementation of <code>printf</code>.
1636An equivalent Go program using <code>fmt.Printf</code>
1637is around 1.2 MB, but
Rob Pike5cff1902012-02-20 12:42:50 +11001638that includes more powerful run-time support.
Evan Shaw64d85762011-05-22 14:56:12 +10001639</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001640
Rob Pike7d87f3d2011-08-06 11:21:59 +10001641<h3 id="unused_variables_and_imports">
1642Can I stop these complaints about my unused variable/import?</h3>
1643
1644<p>
1645The presence of an unused variable may indicate a bug, while
1646unused imports just slow down compilation.
1647Accumulate enough unused imports in your code tree and
1648things can get very slow.
1649For these reasons, Go allows neither.
1650</p>
1651
1652<p>
1653When developing code, it's common to create these situations
1654temporarily and it can be annoying to have to edit them out before the
Oling Cat018e89f2013-01-24 20:46:33 +11001655program will compile.
Rob Pike7d87f3d2011-08-06 11:21:59 +10001656</p>
1657
1658<p>
1659Some have asked for a compiler option to turn those checks off
1660or at least reduce them to warnings.
1661Such an option has not been added, though,
1662because compiler options should not affect the semantics of the
1663language and because the Go compiler does not report warnings, only
1664errors that prevent compilation.
1665</p>
1666
1667<p>
1668There are two reasons for having no warnings. First, if it's worth
1669complaining about, it's worth fixing in the code. (And if it's not
1670worth fixing, it's not worth mentioning.) Second, having the compiler
1671generate warnings encourages the implementation to warn about weak
1672cases that can make compilation noisy, masking real errors that
1673<em>should</em> be fixed.
1674</p>
1675
1676<p>
1677It's easy to address the situation, though. Use the blank identifier
1678to let unused things persist while you're developing.
1679</p>
1680
1681<pre>
1682import "unused"
1683
1684// This declaration marks the import as used by referencing an
1685// item from the package.
1686var _ = unused.Item // TODO: Delete before committing!
1687
1688func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001689 debugData := debug.Profile()
1690 _ = debugData // Used only during debugging.
1691 ....
Rob Pike7d87f3d2011-08-06 11:21:59 +10001692}
1693</pre>
1694
Andrew Gerrand08575732010-04-21 14:00:56 +10001695<h2 id="Performance">Performance</h2>
1696
1697<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1698Why does Go perform badly on benchmark X?</h3>
1699
1700<p>
1701One of Go's design goals is to approach the performance of C for comparable
Oling Cat018e89f2013-01-24 20:46:33 +11001702programs, yet on some benchmarks it does quite poorly, including several
1703in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries
1704for which versions of comparable performance are not available in Go.
Rob Pikefcfed142012-01-23 08:39:53 -08001705For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a>
1706depends on a multi-precision math package, and the C
Andrew Gerrand08575732010-04-21 14:00:56 +10001707versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
Oling Cat018e89f2013-01-24 20:46:33 +11001708written in optimized assembler).
Rob Pikefcfed142012-01-23 08:39:53 -08001709Benchmarks that depend on regular expressions
1710(<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are
Rob Pike86494442011-11-08 16:26:03 -08001711essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
Andrew Gerrand08575732010-04-21 14:00:56 +10001712mature, highly optimized regular expression libraries like PCRE.
1713</p>
1714
1715<p>
1716Benchmark games are won by extensive tuning and the Go versions of most
1717of the benchmarks need attention. If you measure comparable C
Rob Pikefcfed142012-01-23 08:39:53 -08001718and Go programs
1719(<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 +10001720languages are much closer in raw performance than this suite would
1721indicate.
1722</p>
1723
1724<p>
1725Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001726better, many libraries need major performance work, and the garbage collector
Oling Cat018e89f2013-01-24 20:46:33 +11001727isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
Rob Pikefcfed142012-01-23 08:39:53 -08001728garbage can have a huge effect.)
Andrew Gerrand08575732010-04-21 14:00:56 +10001729</p>
1730
Rob Pike93c4a242011-08-06 07:41:55 +10001731<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001732In any case, Go can often be very competitive.
1733There has been significant improvement in the performance of many programs
1734as the language and tools have developed.
1735See the blog post about
Rob Pike93c4a242011-08-06 07:41:55 +10001736<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1737Go programs</a> for an informative example.
1738
Andrew Gerrand4164d602010-09-29 16:52:22 +10001739<h2 id="change_from_c">Changes from C</h2>
1740
1741<h3 id="different_syntax">
1742Why is the syntax so different from C?</h3>
1743<p>
1744Other than declaration syntax, the differences are not major and stem
1745from two desires. First, the syntax should feel light, without too
1746many mandatory keywords, repetition, or arcana. Second, the language
1747has been designed to be easy to analyze
1748and can be parsed without a symbol table. This makes it much easier
1749to build tools such as debuggers, dependency analyzers, automated
1750documentation extractors, IDE plug-ins, and so on. C and its
1751descendants are notoriously difficult in this regard.
1752</p>
1753
1754<h3 id="declarations_backwards">
1755Why are declarations backwards?</h3>
1756<p>
1757They're only backwards if you're used to C. In C, the notion is that a
1758variable is declared like an expression denoting its type, which is a
1759nice idea, but the type and expression grammars don't mix very well and
1760the results can be confusing; consider function pointers. Go mostly
1761separates expression and type syntax and that simplifies things (using
1762prefix <code>*</code> for pointers is an exception that proves the rule). In C,
1763the declaration
1764</p>
1765<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001766 int* a, b;
Andrew Gerrand4164d602010-09-29 16:52:22 +10001767</pre>
1768<p>
1769declares <code>a</code> to be a pointer but not <code>b</code>; in Go
1770</p>
1771<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001772 var a, b *int
Andrew Gerrand4164d602010-09-29 16:52:22 +10001773</pre>
1774<p>
1775declares both to be pointers. This is clearer and more regular.
1776Also, the <code>:=</code> short declaration form argues that a full variable
1777declaration should present the same order as <code>:=</code> so
1778</p>
1779<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001780 var a uint64 = 1
Andrew Gerrand4164d602010-09-29 16:52:22 +10001781</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001782<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001783has the same effect as
Stefan Nilssonc50074e2012-02-29 15:07:52 -08001784</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001785<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001786 a := uint64(1)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001787</pre>
1788<p>
1789Parsing is also simplified by having a distinct grammar for types that
1790is not just the expression grammar; keywords such as <code>func</code>
1791and <code>chan</code> keep things clear.
1792</p>
1793
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001794<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001795See the article about
Francisco Souza6033a482012-03-13 14:46:08 +11001796<a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
Rob Pike93c4a242011-08-06 07:41:55 +10001797for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001798</p>
1799
Andrew Gerrand4164d602010-09-29 16:52:22 +10001800<h3 id="no_pointer_arithmetic">
1801Why is there no pointer arithmetic?</h3>
1802<p>
1803Safety. Without pointer arithmetic it's possible to create a
1804language that can never derive an illegal address that succeeds
1805incorrectly. Compiler and hardware technology have advanced to the
1806point where a loop using array indices can be as efficient as a loop
1807using pointer arithmetic. Also, the lack of pointer arithmetic can
1808simplify the implementation of the garbage collector.
1809</p>
1810
1811<h3 id="inc_dec">
1812Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
1813<p>
1814Without pointer arithmetic, the convenience value of pre- and postfix
1815increment operators drops. By removing them from the expression
1816hierarchy altogether, expression syntax is simplified and the messy
1817issues around order of evaluation of <code>++</code> and <code>--</code>
1818(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
1819are eliminated as well. The simplification is
1820significant. As for postfix vs. prefix, either would work fine but
1821the postfix version is more traditional; insistence on prefix arose
1822with the STL, a library for a language whose name contains, ironically, a
1823postfix increment.
1824</p>
1825
1826<h3 id="semicolons">
1827Why are there braces but no semicolons? And why can't I put the opening
1828brace on the next line?</h3>
1829<p>
1830Go uses brace brackets for statement grouping, a syntax familiar to
1831programmers who have worked with any language in the C family.
1832Semicolons, however, are for parsers, not for people, and we wanted to
1833eliminate them as much as possible. To achieve this goal, Go borrows
1834a trick from BCPL: the semicolons that separate statements are in the
1835formal grammar but are injected automatically, without lookahead, by
1836the lexer at the end of any line that could be the end of a statement.
1837This works very well in practice but has the effect that it forces a
1838brace style. For instance, the opening brace of a function cannot
1839appear on a line by itself.
1840</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001841
Andrew Gerrand4164d602010-09-29 16:52:22 +10001842<p>
1843Some have argued that the lexer should do lookahead to permit the
1844brace to live on the next line. We disagree. Since Go code is meant
1845to be formatted automatically by
Shenghou Ma97b13ac2012-03-07 08:15:47 +11001846<a href="/cmd/gofmt/"><code>gofmt</code></a>,
Andrew Gerrand4164d602010-09-29 16:52:22 +10001847<i>some</i> style must be chosen. That style may differ from what
1848you've used in C or Java, but Go is a new language and
1849<code>gofmt</code>'s style is as good as any other. More
1850important&mdash;much more important&mdash;the advantages of a single,
1851programmatically mandated format for all Go programs greatly outweigh
1852any perceived disadvantages of the particular style.
1853Note too that Go's style means that an interactive implementation of
1854Go can use the standard syntax one line at a time without special rules.
1855</p>
1856
1857<h3 id="garbage_collection">
1858Why do garbage collection? Won't it be too expensive?</h3>
1859<p>
1860One of the biggest sources of bookkeeping in systems programs is
1861memory management. We feel it's critical to eliminate that
1862programmer overhead, and advances in garbage collection
1863technology in the last few years give us confidence that we can
1864implement it with low enough overhead and no significant
Rob Pikefcfed142012-01-23 08:39:53 -08001865latency.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001866</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001867
Andrew Gerrand4164d602010-09-29 16:52:22 +10001868<p>
1869Another point is that a large part of the difficulty of concurrent
1870and multi-threaded programming is memory management;
1871as objects get passed among threads it becomes cumbersome
1872to guarantee they become freed safely.
1873Automatic garbage collection makes concurrent code far easier to write.
1874Of course, implementing garbage collection in a concurrent environment is
1875itself a challenge, but meeting it once rather than in every
1876program helps everyone.
1877</p>
Evan Shaw64d85762011-05-22 14:56:12 +10001878
Andrew Gerrand4164d602010-09-29 16:52:22 +10001879<p>
1880Finally, concurrency aside, garbage collection makes interfaces
1881simpler because they don't need to specify how memory is managed across them.
1882</p>
Rob Pike93c4a242011-08-06 07:41:55 +10001883
1884<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001885The current implementation is a parallel mark-and-sweep
1886collector but a future version might take a different approach.
1887</p>
1888
1889<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001890On the topic of performance, keep in mind that Go gives the programmer
1891considerable control over memory layout and allocation, much more than
1892is typical in garbage-collected languages. A careful programmer can reduce
1893the garbage collection overhead dramatically by using the language well;
1894see the article about
1895<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
1896Go programs</a> for a worked example, including a demonstration of Go's
1897profiling tools.
1898</p>