blob: f273688705df8f9dabc366e57e4ab0ef0d117da4 [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,
Andrew Gerrand43ad89d2014-07-25 10:28:39 +100060<a href="//talks.golang.org/2012/splash.article">Go at Google:
Rob Pike0d5bc0c2013-08-20 06:44:41 +100061Language 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
Andrew Gerrand43ad89d2014-07-25 10:28:39 +100069Go 1 was <a href="//blog.golang.org/2012/03/go-version-1-is-released.html">released</a>
Rob Pike8de50802012-07-16 13:31:15 -070070on 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
Rob Pikebdecae92009-11-23 17:34:23 -080095<h3 id="Whats_the_origin_of_the_mascot">
96What's the origin of the mascot?</h3>
97
98<p>
99The mascot and logo were designed by
100<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
Andrew Gerrand39304eb2016-02-05 09:43:46 +1100101<a href="https://9p.io/plan9/glenda.html">Glenda</a>,
Rob Pikebdecae92009-11-23 17:34:23 -0800102the Plan 9 bunny.
Rob Pike694b2442015-06-29 13:27:41 +1000103The <a href="https://blog.golang.org/gopher">gopher</a>
104is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
Rob Pikebdecae92009-11-23 17:34:23 -0800105T-shirt design some years ago.
106The logo and mascot are covered by the
107<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
108license.
109</p>
110
Andrew Gerrand4164d602010-09-29 16:52:22 +1000111<h3 id="history">
112What is the history of the project?</h3>
113<p>
114Robert Griesemer, Rob Pike and Ken Thompson started sketching the
115goals for a new language on the white board on September 21, 2007.
116Within a few days the goals had settled into a plan to do something
117and a fair idea of what it would be. Design continued part-time in
118parallel with unrelated work. By January 2008, Ken had started work
119on a compiler with which to explore ideas; it generated C code as its
120output. By mid-year the language had become a full-time project and
121had settled enough to attempt a production compiler. In May 2008,
122Ian Taylor independently started on a GCC front end for Go using the
123draft specification. Russ Cox joined in late 2008 and helped move the language
124and libraries from prototype to reality.
125</p>
126
127<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000128Go became a public open source project on November 10, 2009.
129Many people from the community have contributed ideas, discussions, and code.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000130</p>
131
Andrew Gerrand4164d602010-09-29 16:52:22 +1000132<h3 id="creating_a_new_language">
133Why are you creating a new language?</h3>
134<p>
135Go was born out of frustration with existing languages and
136environments for systems programming. Programming had become too
137difficult and the choice of languages was partly to blame. One had to
138choose either efficient compilation, efficient execution, or ease of
139programming; all three were not available in the same mainstream
140language. Programmers who could were choosing ease over
141safety and efficiency by moving to dynamically typed languages such as
142Python and JavaScript rather than C++ or, to a lesser extent, Java.
143</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000144
Andrew Gerrand4164d602010-09-29 16:52:22 +1000145<p>
146Go is an attempt to combine the ease of programming of an interpreted,
147dynamically typed
148language with the efficiency and safety of a statically typed, compiled language.
149It also aims to be modern, with support for networked and multicore
Rob Pike694b2442015-06-29 13:27:41 +1000150computing. Finally, working with Go is intended to be <i>fast</i>: it should take
Andrew Gerrand4164d602010-09-29 16:52:22 +1000151at most a few seconds to build a large executable on a single computer.
152To meet these goals required addressing a number of
153linguistic issues: an expressive but lightweight type system;
154concurrency and garbage collection; rigid dependency specification;
155and so on. These cannot be addressed well by libraries or tools; a new
156language was called for.
157</p>
158
Rob Pike48ecfc92013-03-27 15:26:57 -0700159<p>
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000160The article <a href="//talks.golang.org/2012/splash.article">Go at Google</a>
Rob Pike48ecfc92013-03-27 15:26:57 -0700161discusses the background and motivation behind the design of the Go language,
162as well as providing more detail about many of the answers presented in this FAQ.
163</p>
164
Andrew Gerrand4164d602010-09-29 16:52:22 +1000165<h3 id="ancestors">
166What are Go's ancestors?</h3>
167<p>
168Go is mostly in the C family (basic syntax),
169with significant input from the Pascal/Modula/Oberon
170family (declarations, packages),
171plus some ideas from languages
172inspired by Tony Hoare's CSP,
173such as Newsqueak and Limbo (concurrency).
174However, it is a new language across the board.
175In every respect the language was designed by thinking
176about what programmers do and how to make programming, at least the
177kind of programming we do, more effective, which means more fun.
178</p>
179
Andrew Gerrand4164d602010-09-29 16:52:22 +1000180<h3 id="principles">
181What are the guiding principles in the design?</h3>
182<p>
183Programming today involves too much bookkeeping, repetition, and
184clerical work. As Dick Gabriel says, &ldquo;Old programs read
185like quiet conversations between a well-spoken research worker and a
186well-studied mechanical colleague, not as a debate with a compiler.
187Who'd have guessed sophistication bought such noise?&rdquo;
188The sophistication is worthwhile&mdash;no one wants to go back to
189the old languages&mdash;but can it be more quietly achieved?
190</p>
191<p>
192Go attempts to reduce the amount of typing in both senses of the word.
193Throughout its design, we have tried to reduce clutter and
194complexity. There are no forward declarations and no header files;
195everything is declared exactly once. Initialization is expressive,
196automatic, and easy to use. Syntax is clean and light on keywords.
197Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
198simple type derivation using the <code>:=</code>
199declare-and-initialize construct. And perhaps most radically, there
200is no type hierarchy: types just <i>are</i>, they don't have to
201announce their relationships. These simplifications allow Go to be
202expressive yet comprehensible without sacrificing, well, sophistication.
203</p>
204<p>
205Another important principle is to keep the concepts orthogonal.
206Methods can be implemented for any type; structures represent data while
207interfaces represent abstraction; and so on. Orthogonality makes it
208easier to understand what happens when things combine.
209</p>
210
Russ Cox32274452009-10-22 00:13:51 -0700211<h2 id="Usage">Usage</h2>
212
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000213<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
Rob Pike7685a672009-11-09 20:25:45 -0800214
Evan Shaw64d85762011-05-22 14:56:12 +1000215<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100216Yes. There are now several Go programs deployed in
Rob Pikefcfed142012-01-23 08:39:53 -0800217production inside Google. A public example is the server behind
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000218<a href="//golang.org">golang.org</a>.
Rob Pikefcfed142012-01-23 08:39:53 -0800219It's just the <a href="/cmd/godoc"><code>godoc</code></a>
220document server running in a production configuration on
Dave Cheney82cbcb02012-07-11 09:41:08 -0700221<a href="https://developers.google.com/appengine/">Google App Engine</a>.
Evan Shaw64d85762011-05-22 14:56:12 +1000222</p>
Rob Pike7685a672009-11-09 20:25:45 -0800223
Rob Pike48ecfc92013-03-27 15:26:57 -0700224<p>
Emil Hessmanf3de2172014-12-30 06:45:24 +0100225Other examples include the <a href="//github.com/youtube/vitess/">Vitess</a>
Rob Pike48ecfc92013-03-27 15:26:57 -0700226system for large-scale SQL installations and Google's download server, <code>dl.google.com</code>,
227which delivers Chrome binaries and other large installables such as <code>apt-get</code>
228packages.
229</p>
230
Russ Cox32274452009-10-22 00:13:51 -0700231<h3 id="Do_Go_programs_link_with_Cpp_programs">
232Do Go programs link with C/C++ programs?</h3>
233
234<p>
Andrew Gerrand2a5879d2012-03-20 13:50:05 +1100235There are two Go compiler implementations, <code>gc</code>
Aaron Jacobs86286882015-06-24 09:50:12 +1000236and <code>gccgo</code>.
Rob Pike0c2a4792009-11-01 20:50:42 -0800237<code>Gc</code> uses a different calling convention and linker and can
Russ Cox32274452009-10-22 00:13:51 -0700238therefore only be linked with C programs using the same convention.
Oling Cat018e89f2013-01-24 20:46:33 +1100239There is such a C compiler but no C++ compiler.
240<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
241GCC-compiled C or C++ programs.
Evan Shaw64d85762011-05-22 14:56:12 +1000242</p>
Russ Cox32274452009-10-22 00:13:51 -0700243
244<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100245The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
246&ldquo;foreign function interface&rdquo; to allow safe calling of
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000247C libraries from Go code. SWIG extends this capability to C++ libraries.
Evan Shaw64d85762011-05-22 14:56:12 +1000248</p>
249
Russ Cox32274452009-10-22 00:13:51 -0700250
Rob Pike0c2a4792009-11-01 20:50:42 -0800251<h3 id="Does_Go_support_Google_protocol_buffers">
252Does Go support Google's protocol buffers?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700253
254<p>
Rob Pike6b3031b2010-03-23 17:03:28 -0700255A separate open source project provides the necessary compiler plugin and library.
256It is available at
Emil Hessmanf3de2172014-12-30 06:45:24 +0100257<a href="//github.com/golang/protobuf">github.com/golang/protobuf/</a>
Rob Pike6b3031b2010-03-23 17:03:28 -0700258</p>
Russ Cox32274452009-10-22 00:13:51 -0700259
Evan Shaw64d85762011-05-22 14:56:12 +1000260
Russ Cox6301fb42009-12-03 17:23:33 -0800261<h3 id="Can_I_translate_the_Go_home_page">
262Can I translate the Go home page into another language?</h3>
263
264<p>
265Absolutely. We encourage developers to make Go Language sites in their own languages.
Andrew Gerrand08575732010-04-21 14:00:56 +1000266However, if you choose to add the Google logo or branding to your site
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000267(it does not appear on <a href="//golang.org/">golang.org</a>),
Russ Cox6301fb42009-12-03 17:23:33 -0800268you will need to abide by the guidelines at
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000269<a href="//www.google.com/permissions/guidelines.html">www.google.com/permissions/guidelines.html</a>
Russ Cox6301fb42009-12-03 17:23:33 -0800270</p>
271
Russ Cox32274452009-10-22 00:13:51 -0700272<h2 id="Design">Design</h2>
273
Rob Piked1a19232016-08-27 12:09:38 +1000274<h3 id="runtime">
275Does Go have a runtime?</h3>
276
277<p>
278Go does have an extensive library, called the <em>runtime</em>,
279that is part of every Go program.
280The runtime library implements garbage collection, concurrency,
281stack management, and other critical features of the Go language.
282Although it is more central to the language, Go's runtime is analogous
283to <code>libc</code>, the C library.
284</p>
285
286<p>
287It is important to understand, however, that Go's runtime does not
288include a virtual machine, such as is provided by the Java runtime.
289Go programs are compiled ahead of time to native machine code.
290Thus, although the term is often used to describe the virtual
291environment in which a program runs, in Go the word &ldquo;runtime&rdquo;
292is just the name given to the library providing critical language services.
293</p>
294
Andrew Gerrand4164d602010-09-29 16:52:22 +1000295<h3 id="unicode_identifiers">
296What's up with Unicode identifiers?</h3>
297
298<p>
299It was important to us to extend the space of identifiers from the
300confines of ASCII. Go's rule&mdash;identifier characters must be
301letters or digits as defined by Unicode&mdash;is simple to understand
302and to implement but has restrictions. Combining characters are
303excluded by design, for instance.
304Until there
305is an agreed external definition of what an identifier might be,
306plus a definition of canonicalization of identifiers that guarantees
307no ambiguity, it seemed better to keep combining characters out of
308the mix. Thus we have a simple rule that can be expanded later
309without breaking programs, one that avoids bugs that would surely arise
310from a rule that admits ambiguous identifiers.
311</p>
312
313<p>
314On a related note, since an exported identifier must begin with an
315upper-case letter, identifiers created from &ldquo;letters&rdquo;
316in some languages can, by definition, not be exported. For now the
317only solution is to use something like <code>X日本語</code>, which
318is clearly unsatisfactory; we are considering other options. The
319case-for-visibility rule is unlikely to change however; it's one
320of our favorite features of Go.
321</p>
322
323<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700324
325<p>
326Every language contains novel features and omits someone's favorite
327feature. Go was designed with an eye on felicity of programming, speed of
328compilation, orthogonality of concepts, and the need to support features
329such as concurrency and garbage collection. Your favorite feature may be
330missing because it doesn't fit, because it affects compilation speed or
331clarity of design, or because it would make the fundamental system model
332too difficult.
Evan Shaw64d85762011-05-22 14:56:12 +1000333</p>
Russ Cox32274452009-10-22 00:13:51 -0700334
335<p>
Rob Pike0c2a4792009-11-01 20:50:42 -0800336If it bothers you that Go is missing feature <var>X</var>,
337please forgive us and investigate the features that Go does have. You might find that
Russ Cox32274452009-10-22 00:13:51 -0700338they compensate in interesting ways for the lack of <var>X</var>.
Evan Shaw64d85762011-05-22 14:56:12 +1000339</p>
Russ Cox32274452009-10-22 00:13:51 -0700340
Andrew Gerrand4164d602010-09-29 16:52:22 +1000341<h3 id="generics">
342Why does Go not have generic types?</h3>
343<p>
344Generics may well be added at some point. We don't feel an urgency for
345them, although we understand some programmers do.
346</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000347
Andrew Gerrand4164d602010-09-29 16:52:22 +1000348<p>
349Generics are convenient but they come at a cost in
350complexity in the type system and run-time. We haven't yet found a
351design that gives value proportionate to the complexity, although we
352continue to think about it. Meanwhile, Go's built-in maps and slices,
353plus the ability to use the empty interface to construct containers
354(with explicit unboxing) mean in many cases it is possible to write
355code that does what generics would enable, if less smoothly.
356</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000357
Andrew Gerrand4164d602010-09-29 16:52:22 +1000358<p>
Rob Pikebc33dd72016-04-20 08:56:33 -0700359The topic remains open.
360For a look at several previous unsuccessful attempts to
361design a good generics solution for Go, see
362<a href="https://golang.org/issue/15292">this proposal</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000363</p>
364
365<h3 id="exceptions">
366Why does Go not have exceptions?</h3>
367<p>
368We believe that coupling exceptions to a control
369structure, as in the <code>try-catch-finally</code> idiom, results in
370convoluted code. It also tends to encourage programmers to label
371too many ordinary errors, such as failing to open a file, as
372exceptional.
373</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000374
Andrew Gerrand4164d602010-09-29 16:52:22 +1000375<p>
Rob Pike93c4a242011-08-06 07:41:55 +1000376Go takes a different approach. For plain error handling, Go's multi-value
377returns make it easy to report an error without overloading the return value.
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100378<a href="/doc/articles/error_handling.html">A canonical error type, coupled
379with Go's other features</a>, makes error handling pleasant but quite different
380from that in other languages.
Rob Pike93c4a242011-08-06 07:41:55 +1000381</p>
382
383<p>
384Go also has a couple
Andrew Gerrand4164d602010-09-29 16:52:22 +1000385of built-in functions to signal and recover from truly exceptional
386conditions. The recovery mechanism is executed only as part of a
387function's state being torn down after an error, which is sufficient
388to handle catastrophe but requires no extra control structures and,
389when used well, can result in clean error-handling code.
390</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000391
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000392<p>
Shenghou Ma97b13ac2012-03-07 08:15:47 +1100393See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +1000394</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000395
Andrew Gerrand4164d602010-09-29 16:52:22 +1000396<h3 id="assertions">
397Why does Go not have assertions?</h3>
Russ Cox32274452009-10-22 00:13:51 -0700398
399<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000400Go doesn't provide assertions. They are undeniably convenient, but our
401experience has been that programmers use them as a crutch to avoid thinking
402about proper error handling and reporting. Proper error handling means that
403servers continue operation after non-fatal errors instead of crashing.
404Proper error reporting means that errors are direct and to the point,
405saving the programmer from interpreting a large crash trace. Precise
406errors are particularly important when the programmer seeing the errors is
407not familiar with the code.
Evan Shaw64d85762011-05-22 14:56:12 +1000408</p>
Russ Cox32274452009-10-22 00:13:51 -0700409
Andrew Gerrand4164d602010-09-29 16:52:22 +1000410<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000411We understand that this is a point of contention. There are many things in
412the Go language and libraries that differ from modern practices, simply
413because we feel it's sometimes worth trying a different approach.
Evan Shaw64d85762011-05-22 14:56:12 +1000414</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000415
416<h3 id="csp">
417Why build concurrency on the ideas of CSP?</h3>
418<p>
419Concurrency and multi-threaded programming have a reputation
Rob Pikefcfed142012-01-23 08:39:53 -0800420for difficulty. We believe this is due partly to complex
Andrew Gerrand4164d602010-09-29 16:52:22 +1000421designs such as pthreads and partly to overemphasis on low-level details
Rob Pike93c4a242011-08-06 07:41:55 +1000422such as mutexes, condition variables, and memory barriers.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000423Higher-level interfaces enable much simpler code, even if there are still
424mutexes and such under the covers.
425</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000426
Andrew Gerrand4164d602010-09-29 16:52:22 +1000427<p>
428One of the most successful models for providing high-level linguistic support
429for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
430Occam and Erlang are two well known languages that stem from CSP.
431Go's concurrency primitives derive from a different part of the family tree
432whose main contribution is the powerful notion of channels as first class objects.
Rob Pike48ecfc92013-03-27 15:26:57 -0700433Experience with several earlier languages has shown that the CSP model
434fits well into a procedural language framework.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000435</p>
436
437<h3 id="goroutines">
438Why goroutines instead of threads?</h3>
439<p>
440Goroutines are part of making concurrency easy to use. The idea, which has
441been around for a while, is to multiplex independently executing
Rob Pike93c4a242011-08-06 07:41:55 +1000442functions&mdash;coroutines&mdash;onto a set of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000443When a coroutine blocks, such as by calling a blocking system call,
444the run-time automatically moves other coroutines on the same operating
445system thread to a different, runnable thread so they won't be blocked.
446The programmer sees none of this, which is the point.
Rob Pike287967f2014-03-21 13:59:30 +1100447The result, which we call goroutines, can be very cheap: they have little
448overhead beyond the memory for the stack, which is just a few kilobytes.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000449</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000450
Andrew Gerrand4164d602010-09-29 16:52:22 +1000451<p>
Rob Pike287967f2014-03-21 13:59:30 +1100452To make the stacks small, Go's run-time uses resizable, bounded stacks. A newly
Andrew Gerrand4164d602010-09-29 16:52:22 +1000453minted goroutine is given a few kilobytes, which is almost always enough.
Rob Pike287967f2014-03-21 13:59:30 +1100454When it isn't, the run-time grows (and shrinks) the memory for storing
455the stack automatically, allowing many goroutines to live in a modest
456amount of memory.
457The CPU overhead averages about three cheap instructions per function call.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000458It is practical to create hundreds of thousands of goroutines in the same
Rob Pike287967f2014-03-21 13:59:30 +1100459address space.
460If goroutines were just threads, system resources would
Andrew Gerrand4164d602010-09-29 16:52:22 +1000461run out at a much smaller number.
462</p>
463
464<h3 id="atomic_maps">
465Why are map operations not defined to be atomic?</h3>
466
467<p>
468After long discussion it was decided that the typical use of maps did not require
Ian Lance Taylor81896052013-12-12 18:48:40 -0800469safe access from multiple goroutines, and in those cases where it did, the map was
Andrew Gerrand4164d602010-09-29 16:52:22 +1000470probably part of some larger data structure or computation that was already
471synchronized. Therefore requiring that all map operations grab a mutex would slow
472down most programs and add safety to few. This was not an easy decision,
473however, since it means uncontrolled map access can crash the program.
474</p>
475
476<p>
477The language does not preclude atomic map updates. When required, such
478as when hosting an untrusted program, the implementation could interlock
479map access.
480</p>
481
Ian Lance Taylor984e81f2018-01-19 09:34:24 -0800482<p>
483Map access is unsafe only when updates are occurring.
484As long as all goroutines are only reading—looking up elements in the map,
485including iterating through it using a
486<code>for</code> <code>range</code> loop—and not changing the map
487by assigning to elements or doing deletions,
488it is safe for them to access the map concurrently without synchronization.
489</p>
490
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700491<h3 id="language_changes">
492Will you accept my language change?</h3>
493
494<p>
495People often suggest improvements to the language—the
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000496<a href="//groups.google.com/group/golang-nuts">mailing list</a>
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700497contains a rich history of such discussions—but very few of these changes have
498been accepted.
499</p>
500
501<p>
502Although Go is an open source project, the language and libraries are protected
503by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents
504changes that break existing programs.
505If your proposal violates the Go 1 specification we cannot even entertain the
506idea, regardless of its merit.
507A future major release of Go may be incompatible with Go 1, but we're not ready
508to start talking about what that might be.
509</p>
510
511<p>
Rob Pike61f3fdc2013-08-25 23:50:44 +1000512Even if your proposal is compatible with the Go 1 spec, it might
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700513not be in the spirit of Go's design goals.
Andrew Gerrand43ad89d2014-07-25 10:28:39 +1000514The article <i><a href="//talks.golang.org/2012/splash.article">Go
Andrew Gerrand61dbc342013-05-06 15:02:56 -0700515at Google: Language Design in the Service of Software Engineering</a></i>
516explains Go's origins and the motivation behind its design.
517</p>
518
Andrew Gerrand4164d602010-09-29 16:52:22 +1000519<h2 id="types">Types</h2>
Russ Cox32274452009-10-22 00:13:51 -0700520
521<h3 id="Is_Go_an_object-oriented_language">
522Is Go an object-oriented language?</h3>
523
524<p>
525Yes and no. Although Go has types and methods and allows an
526object-oriented style of programming, there is no type hierarchy.
Russ Coxe434f1a2009-11-07 17:31:22 -0800527The concept of &ldquo;interface&rdquo; in Go provides a different approach that
Russ Cox32274452009-10-22 00:13:51 -0700528we believe is easy to use and in some ways more general. There are
529also ways to embed types in other types to provide something
530analogous&mdash;but not identical&mdash;to subclassing.
Rob Pike0c2a4792009-11-01 20:50:42 -0800531Moreover, methods in Go are more general than in C++ or Java:
Rob Pikefcfed142012-01-23 08:39:53 -0800532they can be defined for any sort of data, even built-in types such
533as plain, &ldquo;unboxed&rdquo; integers.
534They are not restricted to structs (classes).
Evan Shaw64d85762011-05-22 14:56:12 +1000535</p>
Russ Cox32274452009-10-22 00:13:51 -0700536
537<p>
Rob Pike694b2442015-06-29 13:27:41 +1000538Also, the lack of a type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
Russ Coxe434f1a2009-11-07 17:31:22 -0800539lightweight than in languages such as C++ or Java.
Evan Shaw64d85762011-05-22 14:56:12 +1000540</p>
Russ Cox32274452009-10-22 00:13:51 -0700541
542<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
543How do I get dynamic dispatch of methods?</h3>
544
545<p>
546The only way to have dynamically dispatched methods is through an
Rob Pikefcfed142012-01-23 08:39:53 -0800547interface. Methods on a struct or any other concrete type are always resolved statically.
Evan Shaw64d85762011-05-22 14:56:12 +1000548</p>
Russ Cox32274452009-10-22 00:13:51 -0700549
Andrew Gerrand4164d602010-09-29 16:52:22 +1000550<h3 id="inheritance">
551Why is there no type inheritance?</h3>
552<p>
553Object-oriented programming, at least in the best-known languages,
554involves too much discussion of the relationships between types,
555relationships that often could be derived automatically. Go takes a
556different approach.
557</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000558
Andrew Gerrand4164d602010-09-29 16:52:22 +1000559<p>
560Rather than requiring the programmer to declare ahead of time that two
561types are related, in Go a type automatically satisfies any interface
562that specifies a subset of its methods. Besides reducing the
563bookkeeping, this approach has real advantages. Types can satisfy
564many interfaces at once, without the complexities of traditional
565multiple inheritance.
Rob Pike93c4a242011-08-06 07:41:55 +1000566Interfaces can be very lightweight&mdash;an interface with
567one or even zero methods can express a useful concept.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000568Interfaces can be added after the fact if a new idea comes along
569or for testing&mdash;without annotating the original types.
570Because there are no explicit relationships between types
571and interfaces, there is no type hierarchy to manage or discuss.
572</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000573
Andrew Gerrand4164d602010-09-29 16:52:22 +1000574<p>
575It's possible to use these ideas to construct something analogous to
576type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
577enables formatted printing to any output, not just a file, or how the
578<code>bufio</code> package can be completely separate from file I/O,
Rob Pike86494442011-11-08 16:26:03 -0800579or how the <code>image</code> packages generate compressed
580image files. All these ideas stem from a single interface
Andrew Gerrand4164d602010-09-29 16:52:22 +1000581(<code>io.Writer</code>) representing a single method
582(<code>Write</code>). And that's only scratching the surface.
Rob Pike5cff1902012-02-20 12:42:50 +1100583Go's interfaces have a profound influence on how programs are structured.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000584</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000585
Andrew Gerrand4164d602010-09-29 16:52:22 +1000586<p>
587It takes some getting used to but this implicit style of type
Rob Pike93c4a242011-08-06 07:41:55 +1000588dependency is one of the most productive things about Go.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000589</p>
590
591<h3 id="methods_on_basics">
592Why is <code>len</code> a function and not a method?</h3>
593<p>
594We debated this issue but decided
595implementing <code>len</code> and friends as functions was fine in practice and
596didn't complicate questions about the interface (in the Go type sense)
597of basic types.
598</p>
599
600<h3 id="overloading">
601Why does Go not support overloading of methods and operators?</h3>
602<p>
603Method dispatch is simplified if it doesn't need to do type matching as well.
604Experience with other languages told us that having a variety of
605methods with the same name but different signatures was occasionally useful
606but that it could also be confusing and fragile in practice. Matching only by name
607and requiring consistency in the types was a major simplifying decision
608in Go's type system.
609</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000610
Andrew Gerrand4164d602010-09-29 16:52:22 +1000611<p>
612Regarding operator overloading, it seems more a convenience than an absolute
613requirement. Again, things are simpler without it.
614</p>
615
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100616<h3 id="implements_interface">
617Why doesn't Go have "implements" declarations?</h3>
618
619<p>
620A Go type satisfies an interface by implementing the methods of that interface,
621nothing more. This property allows interfaces to be defined and used without
Rob Pike4be9b832012-09-07 14:01:02 -0700622having to modify existing code. It enables a kind of structural typing that
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100623promotes separation of concerns and improves code re-use, and makes it easier
624to build on patterns that emerge as the code develops.
625The semantics of interfaces is one of the main reasons for Go's nimble,
626lightweight feel.
627</p>
628
629<p>
630See the <a href="#inheritance">question on type inheritance</a> for more detail.
631</p>
632
633<h3 id="guarantee_satisfies_interface">
634How can I guarantee my type satisfies an interface?</h3>
635
636<p>
637You can ask the compiler to check that the type <code>T</code> implements the
Rob Pike694b2442015-06-29 13:27:41 +1000638interface <code>I</code> by attempting an assignment using the zero value for
639<code>T</code> or pointer to <code>T</code>, as appropriate:
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100640</p>
641
642<pre>
643type T struct{}
Rob Pike694b2442015-06-29 13:27:41 +1000644var _ I = T{} // Verify that T implements I.
645var _ I = (*T)(nil) // Verify that *T implements I.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100646</pre>
647
648<p>
Rob Pike694b2442015-06-29 13:27:41 +1000649If <code>T</code> (or <code>*T</code>, accordingly) doesn't implement
650<code>I</code>, the mistake will be caught at compile time.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100651</p>
652
653<p>
654If you wish the users of an interface to explicitly declare that they implement
655it, you can add a method with a descriptive name to the interface's method set.
656For example:
657</p>
658
659<pre>
660type Fooer interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800661 Foo()
662 ImplementsFooer()
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100663}
664</pre>
665
666<p>
667A type must then implement the <code>ImplementsFooer</code> method to be a
Andrew Gerrand393ea2d2011-03-17 16:37:34 +1100668<code>Fooer</code>, clearly documenting the fact and announcing it in
669<a href="/cmd/godoc/">godoc</a>'s output.
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100670</p>
671
672<pre>
673type Bar struct{}
674func (b Bar) ImplementsFooer() {}
675func (b Bar) Foo() {}
676</pre>
677
678<p>
Oling Cat018e89f2013-01-24 20:46:33 +1100679Most code doesn't make use of such constraints, since they limit the utility of
Andrew Gerrandaef4e1c2011-03-04 13:11:07 +1100680the interface idea. Sometimes, though, they're necessary to resolve ambiguities
681among similar interfaces.
682</p>
683
Rob Pike93c4a242011-08-06 07:41:55 +1000684<h3 id="t_and_equal_interface">
685Why doesn't type T satisfy the Equal interface?</h3>
686
687<p>
688Consider this simple interface to represent an object that can compare
689itself with another value:
690</p>
691
692<pre>
693type Equaler interface {
Rob Pikefcfed142012-01-23 08:39:53 -0800694 Equal(Equaler) bool
Rob Pike93c4a242011-08-06 07:41:55 +1000695}
696</pre>
697
698<p>
699and this type, <code>T</code>:
700</p>
701
702<pre>
703type T int
704func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
705</pre>
706
707<p>
708Unlike the analogous situation in some polymorphic type systems,
709<code>T</code> does not implement <code>Equaler</code>.
710The argument type of <code>T.Equal</code> is <code>T</code>,
711not literally the required type <code>Equaler</code>.
712</p>
713
714<p>
715In Go, the type system does not promote the argument of
716<code>Equal</code>; that is the programmer's responsibility, as
717illustrated by the type <code>T2</code>, which does implement
718<code>Equaler</code>:
719</p>
720
721<pre>
722type T2 int
723func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
724</pre>
725
726<p>
727Even this isn't like other type systems, though, because in Go <em>any</em>
728type that satisfies <code>Equaler</code> could be passed as the
729argument to <code>T2.Equal</code>, and at run time we must
730check that the argument is of type <code>T2</code>.
731Some languages arrange to make that guarantee at compile time.
732</p>
733
734<p>
735A related example goes the other way:
736</p>
737
738<pre>
739type Opener interface {
David Symondsc9121502013-05-22 12:28:58 +1000740 Open() Reader
Rob Pike93c4a242011-08-06 07:41:55 +1000741}
742
743func (t T3) Open() *os.File
744</pre>
745
746<p>
747In Go, <code>T3</code> does not satisfy <code>Opener</code>,
748although it might in another language.
749</p>
750
751<p>
752While it is true that Go's type system does less for the programmer
753in such cases, the lack of subtyping makes the rules about
754interface satisfaction very easy to state: are the function's names
755and signatures exactly those of the interface?
756Go's rule is also easy to implement efficiently.
757We feel these benefits offset the lack of
Rob Pike694b2442015-06-29 13:27:41 +1000758automatic type promotion. Should Go one day adopt some form of polymorphic
Rob Pike93c4a242011-08-06 07:41:55 +1000759typing, we expect there would be a way to express the idea of these
760examples and also have them be statically checked.
761</p>
762
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000763<h3 id="convert_slice_of_interface">
764Can I convert a []T to an []interface{}?</h3>
765
766<p>
Rob Pike86494442011-11-08 16:26:03 -0800767Not directly, because they do not have the same representation in memory.
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000768It is necessary to copy the elements individually to the destination
769slice. This example converts a slice of <code>int</code> to a slice of
770<code>interface{}</code>:
771</p>
772
773<pre>
774t := []int{1, 2, 3, 4}
775s := make([]interface{}, len(t))
776for i, v := range t {
Rob Pikefcfed142012-01-23 08:39:53 -0800777 s[i] = v
Andrew Gerrand17805dd2011-06-18 20:31:38 +1000778}
779</pre>
780
Ian Lance Taylorfbf92432016-11-16 11:23:53 -0800781<h3 id="convert_slice_with_same_underlying_type">
782Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?</h3>
783
784This last line of this code sample does not compile.
785
786<pre>
787type T1 int
788type T2 int
789var t1 T1
790var x = T2(t1) // OK
791var st1 []T1
792var sx = ([]T2)(st1) // NOT OK
793</pre>
794
795<p>
796In Go, types are closely tied to methods, in that every named type has
797a (possibly empty) method set.
798The general rule is that you can change the name of the type being
799converted (and thus possibly change its method set) but you can't
800change the name (and method set) of elements of a composite type.
801Go requires you to be explicit about type conversions.
802</p>
803
Rob Pike1e0f97a2012-02-17 16:27:17 +1100804<h3 id="nil_error">
805Why is my nil error value not equal to nil?
806</h3>
807
808<p>
809Under the covers, interfaces are implemented as two elements, a type and a value.
810The value, called the interface's dynamic value,
811is an arbitrary concrete value and the type is that of the value.
812For the <code>int</code> value 3, an interface value contains,
813schematically, (<code>int</code>, <code>3</code>).
814</p>
815
816<p>
817An interface value is <code>nil</code> only if the inner value and type are both unset,
818(<code>nil</code>, <code>nil</code>).
819In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
Rob Pike694b2442015-06-29 13:27:41 +1000820If we store a <code>nil</code> pointer of type <code>*int</code> inside
Rob Pike1e0f97a2012-02-17 16:27:17 +1100821an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
822(<code>*int</code>, <code>nil</code>).
823Such an interface value will therefore be non-<code>nil</code>
824<em>even when the pointer inside is</em> <code>nil</code>.
825</p>
826
827<p>
Rob Pike694b2442015-06-29 13:27:41 +1000828This situation can be confusing, and arises when a <code>nil</code> value is
Rob Pike1e0f97a2012-02-17 16:27:17 +1100829stored inside an interface value such as an <code>error</code> return:
830</p>
831
832<pre>
833func returnsError() error {
834 var p *MyError = nil
835 if bad() {
836 p = ErrBad
837 }
838 return p // Will always return a non-nil error.
839}
840</pre>
841
842<p>
843If all goes well, the function returns a <code>nil</code> <code>p</code>,
844so the return value is an <code>error</code> interface
845value holding (<code>*MyError</code>, <code>nil</code>).
846This means that if the caller compares the returned error to <code>nil</code>,
847it will always look as if there was an error even if nothing bad happened.
848To return a proper <code>nil</code> <code>error</code> to the caller,
849the function must return an explicit <code>nil</code>:
850</p>
851
852
853<pre>
854func returnsError() error {
855 if bad() {
856 return ErrBad
857 }
858 return nil
859}
860</pre>
861
862<p>
863It's a good idea for functions
864that return errors always to use the <code>error</code> type in
865their signature (as we did above) rather than a concrete type such
866as <code>*MyError</code>, to help guarantee the error is
867created correctly. As an example,
868<a href="/pkg/os/#Open"><code>os.Open</code></a>
869returns an <code>error</code> even though, if not <code>nil</code>,
870it's always of concrete type
871<a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
872</p>
873
874<p>
875Similar situations to those described here can arise whenever interfaces are used.
876Just keep in mind that if any concrete value
877has been stored in the interface, the interface will not be <code>nil</code>.
878For more information, see
Shenghou Macb6c09a2012-03-01 14:54:35 +0800879<a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
Rob Pike1e0f97a2012-02-17 16:27:17 +1100880</p>
881
882
Rob Pike7d87f3d2011-08-06 11:21:59 +1000883<h3 id="unions">
884Why are there no untagged unions, as in C?</h3>
885
886<p>
887Untagged unions would violate Go's memory safety
888guarantees.
889</p>
890
891<h3 id="variant_types">
892Why does Go not have variant types?</h3>
893
894<p>
895Variant types, also known as algebraic types, provide a way to specify
896that a value might take one of a set of other types, but only those
897types. A common example in systems programming would specify that an
898error is, say, a network error, a security error or an application
899error and allow the caller to discriminate the source of the problem
900by examining the type of the error. Another example is a syntax tree
901in which each node can be a different type: declaration, statement,
902assignment and so on.
903</p>
904
905<p>
906We considered adding variant types to Go, but after discussion
907decided to leave them out because they overlap in confusing ways
908with interfaces. What would happen if the elements of a variant type
909were themselves interfaces?
910</p>
911
912<p>
913Also, some of what variant types address is already covered by the
914language. The error example is easy to express using an interface
915value to hold the error and a type switch to discriminate cases. The
916syntax tree example is also doable, although not as elegantly.
917</p>
918
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800919<h3 id="covariant_types">
920Why does Go not have covariant result types?</h3>
921
922<p>
923Covariant result types would mean that an interface like
Brad Fitzpatricke7191472016-09-20 21:52:11 +0000924</p>
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800925
926<pre>
927type Copyable interface {
928 Copy() interface{}
929}
930</pre>
931
Brad Fitzpatricke7191472016-09-20 21:52:11 +0000932<p>
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800933would be satisfied by the method
Brad Fitzpatricke7191472016-09-20 21:52:11 +0000934</p>
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800935
936<pre>
937func (v Value) Copy() Value
938</pre>
939
Rob Piked1a19232016-08-27 12:09:38 +1000940<p>because <code>Value</code> implements the empty interface.
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800941In Go method types must match exactly, so <code>Value</code> does not
942implement <code>Copyable</code>.
943Go separates the notion of what a
944type does&mdash;its methods&mdash;from the type's implementation.
945If two methods return different types, they are not doing the same thing.
946Programmers who want covariant result types are often trying to
Russ Coxcf49b352015-12-11 11:35:36 -0500947express a type hierarchy through interfaces.
Ian Lance Taylor85dcc342015-11-20 07:00:09 -0800948In Go it's more natural to have a clean separation between interface
949and implementation.
950</p>
951
Andrew Gerrand4164d602010-09-29 16:52:22 +1000952<h2 id="values">Values</h2>
953
954<h3 id="conversions">
955Why does Go not provide implicit numeric conversions?</h3>
956<p>
957The convenience of automatic conversion between numeric types in C is
958outweighed by the confusion it causes. When is an expression unsigned?
959How big is the value? Does it overflow? Is the result portable, independent
960of the machine on which it executes?
961It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
962are not easy to implement and inconsistent across architectures.
963For reasons of portability, we decided to make things clear and straightforward
964at the cost of some explicit conversions in the code.
965The definition of constants in Go&mdash;arbitrary precision values free
966of signedness and size annotations&mdash;ameliorates matters considerably,
967though.
968</p>
Evan Shaw64d85762011-05-22 14:56:12 +1000969
Andrew Gerrand4164d602010-09-29 16:52:22 +1000970<p>
971A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
972are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
973type is generic; if you care about how many bits an integer holds, Go
974encourages you to be explicit.
975</p>
976
Rob Pike56c4d0a2014-09-27 11:56:54 -0700977<p>
Brad Fitzpatrick783297a2015-07-11 08:51:20 -0600978A blog post titled <a href="https://blog.golang.org/constants">Constants</a>
Rob Pike56c4d0a2014-09-27 11:56:54 -0700979explores this topic in more detail.
980</p>
981
Andrew Gerrand4164d602010-09-29 16:52:22 +1000982<h3 id="builtin_maps">
983Why are maps built in?</h3>
984<p>
985The same reason strings are: they are such a powerful and important data
986structure that providing one excellent implementation with syntactic support
987makes programming more pleasant. We believe that Go's implementation of maps
988is strong enough that it will serve for the vast majority of uses.
989If a specific application can benefit from a custom implementation, it's possible
990to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
991</p>
992
Andrew Gerrand4164d602010-09-29 16:52:22 +1000993<h3 id="map_keys">
Rob Pikefcfed142012-01-23 08:39:53 -0800994Why don't maps allow slices as keys?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +1000995<p>
Rob Pikefcfed142012-01-23 08:39:53 -0800996Map lookup requires an equality operator, which slices do not implement.
Andrew Gerrand4164d602010-09-29 16:52:22 +1000997They don't implement equality because equality is not well defined on such types;
998there are multiple considerations involving shallow vs. deep comparison, pointer vs.
Rob Pikefcfed142012-01-23 08:39:53 -0800999value comparison, how to deal with recursive types, and so on.
1000We may revisit this issue&mdash;and implementing equality for slices
Andrew Gerrand4164d602010-09-29 16:52:22 +10001001will not invalidate any existing programs&mdash;but without a clear idea of what
Rob Pike5cff1902012-02-20 12:42:50 +11001002equality of slices should mean, it was simpler to leave it out for now.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001003</p>
1004
Rob Pikefcfed142012-01-23 08:39:53 -08001005<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001006In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
1007types can be used as map keys. Slices still do not have a definition of equality, though.
Rob Pikefcfed142012-01-23 08:39:53 -08001008</p>
1009
Andrew Gerrand4164d602010-09-29 16:52:22 +10001010<h3 id="references">
1011Why are maps, slices, and channels references while arrays are values?</h3>
1012<p>
1013There's a lot of history on that topic. Early on, maps and channels
1014were syntactically pointers and it was impossible to declare or use a
1015non-pointer instance. Also, we struggled with how arrays should work.
1016Eventually we decided that the strict separation of pointers and
Rob Pike48ecfc92013-03-27 15:26:57 -07001017values made the language harder to use. Changing these
1018types to act as references to the associated, shared data structures resolved
1019these issues. This change added some regrettable complexity to the
1020language but had a large effect on usability: Go became a more
1021productive, comfortable language when it was introduced.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001022</p>
1023
Russ Cox32274452009-10-22 00:13:51 -07001024<h2 id="Writing_Code">Writing Code</h2>
1025
1026<h3 id="How_are_libraries_documented">
1027How are libraries documented?</h3>
1028
1029<p>
1030There is a program, <code>godoc</code>, written in Go, that extracts
1031package documentation from the source code. It can be used on the
1032command line or on the web. An instance is running at
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001033<a href="/pkg/">golang.org/pkg/</a>.
Russ Coxe434f1a2009-11-07 17:31:22 -08001034In fact, <code>godoc</code> implements the full site at
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001035<a href="/">golang.org/</a>.
Evan Shaw64d85762011-05-22 14:56:12 +10001036</p>
Russ Cox32274452009-10-22 00:13:51 -07001037
Rob Pike694b2442015-06-29 13:27:41 +10001038<p>
1039A <code>godoc</code> instance may be configured to provide rich,
1040interactive static analyses of symbols in the programs it displays; details are
1041listed <a href="https://golang.org/lib/godoc/analysis/help.html">here</a>.
1042</p>
1043
1044<p>
1045For access to documentation from the command line, the
1046<a href="https://golang.org/pkg/cmd/go/">go</a> tool has a
1047<a href="https://golang.org/pkg/cmd/go/#hdr-Show_documentation_for_package_or_symbol">doc</a>
1048subcommand that provides a textual interface to the same information.
1049</p>
1050
Russ Cox32274452009-10-22 00:13:51 -07001051<h3 id="Is_there_a_Go_programming_style_guide">
1052Is there a Go programming style guide?</h3>
1053
1054<p>
Rob Pike0c2a4792009-11-01 20:50:42 -08001055Eventually, there may be a small number of rules to guide things
1056like naming, layout, and file organization.
1057The document <a href="effective_go.html">Effective Go</a>
1058contains some style advice.
1059More directly, the program <code>gofmt</code> is a pretty-printer
1060whose purpose is to enforce layout rules; it replaces the usual
1061compendium of do's and don'ts that allows interpretation.
1062All the Go code in the repository has been run through <code>gofmt</code>.
Evan Shaw64d85762011-05-22 14:56:12 +10001063</p>
Russ Cox32274452009-10-22 00:13:51 -07001064
Rob Pike3a7fe362014-03-06 13:15:09 +11001065<p>
1066The document titled
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001067<a href="//golang.org/s/comments">Go Code Review Comments</a>
Rob Pike3a7fe362014-03-06 13:15:09 +11001068is a collection of very short essays about details of Go idiom that are often
1069missed by programmers.
1070It is a handy reference for people doing code reviews for Go projects.
1071</p>
1072
Russ Cox32274452009-10-22 00:13:51 -07001073<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
1074How do I submit patches to the Go libraries?</h3>
1075
Rob Pike0c2a4792009-11-01 20:50:42 -08001076<p>
Rob Pike56c4d0a2014-09-27 11:56:54 -07001077The library sources are in the <code>src</code> directory of the repository.
Rob Pike0c2a4792009-11-01 20:50:42 -08001078If you want to make a significant change, please discuss on the mailing list before embarking.
Evan Shaw64d85762011-05-22 14:56:12 +10001079</p>
Russ Cox32274452009-10-22 00:13:51 -07001080
Rob Pike0c2a4792009-11-01 20:50:42 -08001081<p>
1082See the document
1083<a href="contribute.html">Contributing to the Go project</a>
1084for more information about how to proceed.
Evan Shaw64d85762011-05-22 14:56:12 +10001085</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001086
Herbert Georg Fischer99021b72013-03-15 13:43:10 -07001087<h3 id="git_https">
1088Why does "go get" use HTTPS when cloning a repository?</h3>
1089
1090<p>
1091Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
1092and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418
1093(git) and TCP port 22 (SSH).
1094When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
1095default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
1096The <code>go get</code> command therefore uses HTTPS for safety.
1097</p>
1098
1099<p>
1100If you use <code>git</code> and prefer to push changes through SSH using your existing key
1101it's easy to work around this. For GitHub, try one of these solutions:
1102</p>
1103<ul>
1104<li>Manually clone the repository in the expected package directory:
1105<pre>
Russ Cox74628a82016-11-30 14:56:58 -05001106$ cd src/github.com/username
Herbert Georg Fischer99021b72013-03-15 13:43:10 -07001107$ git clone git@github.com:username/package.git
1108</pre>
1109</li>
1110<li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending
1111these two lines to <code>~/.gitconfig</code>:
1112<pre>
1113[url "git@github.com:"]
1114 pushInsteadOf = https://github.com/
1115</pre>
1116</li>
1117</ul>
1118
Russ Coxdc8d9032013-10-03 09:18:47 -04001119<h3 id="get_version">
1120How should I manage package versions using "go get"?</h3>
1121
1122<p>
1123"Go get" does not have any explicit concept of package versions.
1124Versioning is a source of significant complexity, especially in large code bases,
1125and we are unaware of any approach that works well at scale in a large enough
1126variety of situations to be appropriate to force on all Go users.
1127What "go get" and the larger Go toolchain do provide is isolation of
1128packages with different import paths.
1129For example, the standard library's <code>html/template</code> and <code>text/template</code>
1130coexist even though both are "package template".
1131This observation leads to some advice for package authors and package users.
1132</p>
1133
1134<p>
1135Packages intended for public use should try to maintain backwards compatibility as they evolve.
1136The <a href="/doc/go1compat.html">Go 1 compatibility guidelines</a> are a good reference here:
1137don't remove exported names, encourage tagged composite literals, and so on.
1138If different functionality is required, add a new name instead of changing an old one.
1139If a complete break is required, create a new package with a new import path.</p>
1140
1141<p>
1142If you're using an externally supplied package and worry that it might change in
1143unexpected ways, the simplest solution is to copy it to your local repository.
1144(This is the approach Google takes internally.)
1145Store the copy under a new import path that identifies it as a local copy.
1146For example, you might copy "original.com/pkg" to "you.com/external/original.com/pkg".
Rob Pike694b2442015-06-29 13:27:41 +10001147The <a href="https://godoc.org/golang.org/x/tools/cmd/gomvpkg">gomvpkg</a>
1148program is one tool to help automate this process.
1149</p>
1150
1151<p>
sam boyerdc8b4e62017-06-17 01:21:48 -04001152The Go 1.5 release added a facility to the
Rob Pike694b2442015-06-29 13:27:41 +10001153<a href="https://golang.org/cmd/go">go</a> command
1154that makes it easier to manage external dependencies by "vendoring"
1155them into a special directory near the package that depends upon them.
1156See the <a href="https://golang.org/s/go15vendor">design
1157document</a> for details.
Russ Coxdc8d9032013-10-03 09:18:47 -04001158</p>
1159
sam boyerdc8b4e62017-06-17 01:21:48 -04001160<p>
1161Work is underway on an experimental package management tool,
1162<a href="https://github.com/golang/dep"><code>dep</code></a>, to learn
1163more about how tooling can help package management. More information can be found in
Alberto Donizettidfd6b6e2017-12-06 11:42:42 +01001164<a href="https://github.com/golang/dep/blob/master/docs/FAQ.md">the <code>dep</code> FAQ</a>.
sam boyerdc8b4e62017-06-17 01:21:48 -04001165</p>
1166
Andrew Gerrand4164d602010-09-29 16:52:22 +10001167<h2 id="Pointers">Pointers and Allocation</h2>
1168
1169<h3 id="pass_by_value">
1170When are function parameters passed by value?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001171
1172<p>
Rob Pike86494442011-11-08 16:26:03 -08001173As in all languages in the C family, everything in Go is passed by value.
1174That is, a function always gets a copy of the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001175thing being passed, as if there were an assignment statement assigning the
Rob Pike86494442011-11-08 16:26:03 -08001176value to the parameter. For instance, passing an <code>int</code> value
1177to a function makes a copy of the <code>int</code>, and passing a pointer
1178value makes a copy of the pointer, but not the data it points to.
Rob Pike694b2442015-06-29 13:27:41 +10001179(See a <a href="/doc/faq#methods_on_values_or_pointers">later
1180section</a> for a discussion of how this affects method receivers.)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001181</p>
Russ Cox32274452009-10-22 00:13:51 -07001182
1183<p>
Rob Pikefcfed142012-01-23 08:39:53 -08001184Map and slice values behave like pointers: they are descriptors that
Andrew Gerrand4164d602010-09-29 16:52:22 +10001185contain pointers to the underlying map or slice data. Copying a map or
1186slice value doesn't copy the data it points to. Copying an interface value
1187makes a copy of the thing stored in the interface value. If the interface
1188value holds a struct, copying the interface value makes a copy of the
1189struct. If the interface value holds a pointer, copying the interface value
Oling Cat018e89f2013-01-24 20:46:33 +11001190makes a copy of the pointer, but again not the data it points to.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001191</p>
1192
Russ Coxafe675c2016-10-20 14:37:31 -04001193<p>
1194Note that this discussion is about the semantics of the operations.
1195Actual implementations may apply optimizations to avoid copying
1196as long as the optimizations do not change the semantics.
1197</p>
1198
Rob Pike09cd13c2013-03-15 11:38:50 -07001199<h3 id="pointer_to_interface">
1200When should I use a pointer to an interface?</h3>
1201
1202<p>
1203Almost never. Pointers to interface values arise only in rare, tricky situations involving
1204disguising an interface value's type for delayed evaluation.
1205</p>
1206
1207<p>
1208It is however a common mistake to pass a pointer to an interface value
1209to a function expecting an interface. The compiler will complain about this
1210error but the situation can still be confusing, because sometimes a
1211<a href="#different_method_sets">pointer
1212is necessary to satisfy an interface</a>.
1213The insight is that although a pointer to a concrete type can satisfy
Rob Pikea9422652014-10-26 11:27:55 -07001214an interface, with one exception <em>a pointer to an interface can never satisfy an interface</em>.
Rob Pike09cd13c2013-03-15 11:38:50 -07001215</p>
1216
1217<p>
1218Consider the variable declaration,
1219</p>
1220
1221<pre>
1222var w io.Writer
1223</pre>
1224
1225<p>
1226The printing function <code>fmt.Fprintf</code> takes as its first argument
1227a value that satisfies <code>io.Writer</code>—something that implements
1228the canonical <code>Write</code> method. Thus we can write
1229</p>
1230
1231<pre>
1232fmt.Fprintf(w, "hello, world\n")
1233</pre>
1234
1235<p>
1236If however we pass the address of <code>w</code>, the program will not compile.
1237</p>
1238
1239<pre>
1240fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
1241</pre>
1242
1243<p>
1244The one exception is that any value, even a pointer to an interface, can be assigned to
1245a variable of empty interface type (<code>interface{}</code>).
1246Even so, it's almost certainly a mistake if the value is a pointer to an interface;
1247the result can be confusing.
1248</p>
1249
Andrew Gerrand4164d602010-09-29 16:52:22 +10001250<h3 id="methods_on_values_or_pointers">
1251Should I define methods on values or pointers?</h3>
1252
1253<pre>
Rob Pike93c4a242011-08-06 07:41:55 +10001254func (s *MyStruct) pointerMethod() { } // method on pointer
1255func (s MyStruct) valueMethod() { } // method on value
Andrew Gerrand4164d602010-09-29 16:52:22 +10001256</pre>
Russ Cox32274452009-10-22 00:13:51 -07001257
1258<p>
Rob Pike93c4a242011-08-06 07:41:55 +10001259For programmers unaccustomed to pointers, the distinction between these
1260two examples can be confusing, but the situation is actually very simple.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001261When defining a method on a type, the receiver (<code>s</code> in the above
Rob Pike5cff1902012-02-20 12:42:50 +11001262examples) behaves exactly as if it were an argument to the method.
Rob Pike93c4a242011-08-06 07:41:55 +10001263Whether to define the receiver as a value or as a pointer is the same
1264question, then, as whether a function argument should be a value or
1265a pointer.
1266There are several considerations.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001267</p>
1268
Rob Pike93c4a242011-08-06 07:41:55 +10001269<p>
1270First, and most important, does the method need to modify the
1271receiver?
1272If it does, the receiver <em>must</em> be a pointer.
Rob Pike48ecfc92013-03-27 15:26:57 -07001273(Slices and maps act as references, so their story is a little
Rob Pike93c4a242011-08-06 07:41:55 +10001274more subtle, but for instance to change the length of a slice
1275in a method the receiver must still be a pointer.)
1276In the examples above, if <code>pointerMethod</code> modifies
1277the fields of <code>s</code>,
1278the caller will see those changes, but <code>valueMethod</code>
1279is called with a copy of the caller's argument (that's the definition
1280of passing a value), so changes it makes will be invisible to the caller.
1281</p>
1282
1283<p>
1284By the way, pointer receivers are identical to the situation in Java,
1285although in Java the pointers are hidden under the covers; it's Go's
1286value receivers that are unusual.
1287</p>
1288
1289<p>
1290Second is the consideration of efficiency. If the receiver is large,
1291a big <code>struct</code> for instance, it will be much cheaper to
1292use a pointer receiver.
1293</p>
1294
1295<p>
1296Next is consistency. If some of the methods of the type must have
1297pointer receivers, the rest should too, so the method set is
1298consistent regardless of how the type is used.
1299See the section on <a href="#different_method_sets">method sets</a>
1300for details.
1301</p>
1302
1303<p>
1304For types such as basic types, slices, and small <code>structs</code>,
1305a value receiver is very cheap so unless the semantics of the method
1306requires a pointer, a value receiver is efficient and clear.
1307</p>
1308
1309
Andrew Gerrand4164d602010-09-29 16:52:22 +10001310<h3 id="new_and_make">
1311What's the difference between new and make?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001312
1313<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001314In short: <code>new</code> allocates memory, <code>make</code> initializes
1315the slice, map, and channel types.
1316</p>
1317
1318<p>
1319See the <a href="/doc/effective_go.html#allocation_new">relevant section
1320of Effective Go</a> for more details.
1321</p>
1322
Andrew Gerrandaffd1ba2010-12-09 08:59:29 +11001323<h3 id="q_int_sizes">
Rob Pike48ecfc92013-03-27 15:26:57 -07001324What is the size of an <code>int</code> on a 64 bit machine?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001325
1326<p>
Rob Pike80e25fc2011-01-19 23:07:38 -05001327The sizes of <code>int</code> and <code>uint</code> are implementation-specific
1328but the same as each other on a given platform.
Russ Cox10ea6512012-09-24 20:57:01 -04001329For portability, code that relies on a particular
Rob Pike80e25fc2011-01-19 23:07:38 -05001330size of value should use an explicitly sized type, like <code>int64</code>.
Russ Cox10ea6512012-09-24 20:57:01 -04001331Prior to Go 1.1, the 64-bit Go compilers (both gc and gccgo) used
1332a 32-bit representation for <code>int</code>. As of Go 1.1 they use
1333a 64-bit representation.
Terrel Shumwayfcb45e72016-08-30 07:58:52 -06001334</p>
1335
1336<p>
Rob Pike80e25fc2011-01-19 23:07:38 -05001337On the other hand, floating-point scalars and complex
Terrel Shumwayfcb45e72016-08-30 07:58:52 -06001338types are always sized (there are no <code>float</code> or <code>complex</code> basic types),
1339because programmers should be aware of precision when using floating-point numbers.
1340The default type used for an (untyped) floating-point constant is <code>float64</code>.
Robert Griesemer6ebacf12016-08-30 17:09:30 -07001341Thus <code>foo</code> <code>:=</code> <code>3.0</code> declares a variable <code>foo</code>
1342of type <code>float64</code>.
1343For a <code>float32</code> variable initialized by an (untyped) constant, the variable type
1344must be specified explicitly in the variable declaration:
1345</p>
1346
1347<pre>
1348var foo float32 = 3.0
1349</pre>
1350
1351<p>
1352Alternatively, the constant must be given a type with a conversion as in
1353<code>foo := float32(3.0)</code>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001354</p>
1355
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001356<h3 id="stack_or_heap">
1357How do I know whether a variable is allocated on the heap or the stack?</h3>
1358
1359<p>
1360From a correctness standpoint, you don't need to know.
1361Each variable in Go exists as long as there are references to it.
1362The storage location chosen by the implementation is irrelevant to the
1363semantics of the language.
Evan Shaw64d85762011-05-22 14:56:12 +10001364</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001365
1366<p>
1367The storage location does have an effect on writing efficient programs.
1368When possible, the Go compilers will allocate variables that are
1369local to a function in that function's stack frame. However, if the
1370compiler cannot prove that the variable is not referenced after the
1371function returns, then the compiler must allocate the variable on the
1372garbage-collected heap to avoid dangling pointer errors.
Rob Pikefcfed142012-01-23 08:39:53 -08001373Also, if a local variable is very large, it might make more sense
1374to store it on the heap rather than the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001375</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001376
1377<p>
Rob Pike86494442011-11-08 16:26:03 -08001378In the current compilers, if a variable has its address taken, that variable
1379is a candidate for allocation on the heap. However, a basic <em>escape
1380analysis</em> recognizes some cases when such variables will not
1381live past the return from the function and can reside on the stack.
Evan Shaw64d85762011-05-22 14:56:12 +10001382</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001383
Andrew Gerrand21009472012-10-11 14:21:19 +11001384<h3 id="Why_does_my_Go_process_use_so_much_virtual_memory">
1385Why does my Go process use so much virtual memory?</h3>
1386
1387<p>
1388The Go memory allocator reserves a large region of virtual memory as an arena
1389for allocations. This virtual memory is local to the specific Go process; the
1390reservation does not deprive other processes of memory.
1391</p>
1392
1393<p>
1394To find the amount of actual memory allocated to a Go process, use the Unix
1395<code>top</code> command and consult the <code>RES</code> (Linux) or
1396<code>RSIZE</code> (Mac OS X) columns.
1397<!-- TODO(adg): find out how this works on Windows -->
1398</p>
1399
Andrew Gerrand4164d602010-09-29 16:52:22 +10001400<h2 id="Concurrency">Concurrency</h2>
1401
1402<h3 id="What_operations_are_atomic_What_about_mutexes">
1403What operations are atomic? What about mutexes?</h3>
1404
1405<p>
1406We haven't fully defined it all yet, but some details about atomicity are
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001407available in the <a href="/ref/mem">Go Memory Model specification</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001408</p>
1409
1410<p>
1411Regarding mutexes, the <a href="/pkg/sync">sync</a>
1412package implements them, but we hope Go programming style will
1413encourage people to try higher-level techniques. In particular, consider
1414structuring your program so that only one goroutine at a time is ever
1415responsible for a particular piece of data.
1416</p>
1417
1418<p>
1419Do not communicate by sharing memory. Instead, share memory by communicating.
1420</p>
1421
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001422<p>
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001423See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk and its <a href="//blog.golang.org/2010/07/share-memory-by-communicating.html">associated article</a> for a detailed discussion of this concept.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001424</p>
1425
Andrew Gerrand4164d602010-09-29 16:52:22 +10001426<h3 id="Why_no_multi_CPU">
1427Why doesn't my multi-goroutine program use multiple CPUs?</h3>
1428
1429<p>
Rob Pike694b2442015-06-29 13:27:41 +10001430The number of CPUs available simultaneously to executing goroutines is
1431controlled by the <code>GOMAXPROCS</code> shell environment variable.
1432In earlier releases of Go, the default value was 1, but as of Go 1.5 the default
1433value is the number of cores available.
Rob Pikec97e73d2015-06-29 15:43:42 +10001434Therefore programs compiled after 1.5 should demonstrate parallel execution
Rob Pike694b2442015-06-29 13:27:41 +10001435of multiple goroutines.
1436To change the behavior, set the environment variable or use the similarly-named
1437<a href="/pkg/runtime/#GOMAXPROCS">function</a>
1438of the runtime package to configure the
1439run-time support to utilize a different number of threads.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001440</p>
1441
1442<p>
Rob Pike694b2442015-06-29 13:27:41 +10001443Programs that perform parallel computation might benefit from a further increase in
Rob Pike5cff1902012-02-20 12:42:50 +11001444<code>GOMAXPROCS</code>.
Rob Pike48ecfc92013-03-27 15:26:57 -07001445However, be aware that
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001446<a href="//blog.golang.org/2013/01/concurrency-is-not-parallelism.html">concurrency
Rob Pike48ecfc92013-03-27 15:26:57 -07001447is not parallelism</a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001448</p>
1449
1450<h3 id="Why_GOMAXPROCS">
1451Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
1452slower?</h3>
1453
1454<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001455It depends on the nature of your program.
Rob Pike01afb792012-01-26 14:44:38 -08001456Problems that are intrinsically sequential cannot be sped up by adding
1457more goroutines.
1458Concurrency only becomes parallelism when the problem is
1459intrinsically parallel.
1460</p>
1461
1462<p>
1463In practical terms, programs that spend more time
1464communicating on channels than doing computation
Rob Pike694b2442015-06-29 13:27:41 +10001465may experience performance degradation when using
Rob Pike01afb792012-01-26 14:44:38 -08001466multiple OS threads.
1467This is because sending data between threads involves switching
1468contexts, which has significant cost.
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001469For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
Rob Pike01afb792012-01-26 14:44:38 -08001470from the Go specification has no significant parallelism although it launches many
1471goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than
1472to speed it up.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001473</p>
1474
1475<p>
Rob Pike694b2442015-06-29 13:27:41 +10001476Go's goroutine scheduler is not as good as it needs to be, although it
1477has improved in recent releases.
1478In the future, it may better optimize its use of OS threads.
1479For now, if there are performance issues,
1480setting <code>GOMAXPROCS</code> on a per-application basis may help.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001481</p>
1482
Rob Pike48ecfc92013-03-27 15:26:57 -07001483<p>
1484For more detail on this topic see the talk entitled,
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001485<a href="//blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency
Rob Pike48ecfc92013-03-27 15:26:57 -07001486is not Parallelism</a>.
1487
Rob Pike992ce902017-11-28 16:05:59 +11001488<h3 id="no_goroutine_id">
1489Why is there no goroutine ID?</h3>
1490
1491<p>
1492Goroutines do not have names; they are just anonymous workers.
1493They expose no unique identifier, name, or data structure to the programmer.
1494Some people are surprised by this, expecting the <code>go</code>
1495statement to return some item that can be used to access and control
1496the goroutine later.
1497</p>
1498
1499<p>
Rob Pike21672b32017-11-29 16:05:01 +11001500The fundamental reason goroutines are anonymous is so that
1501the full Go language is available when programming concurrent code.
1502By contrast, the usage patterns that develop when threads and goroutines are
Rob Pike992ce902017-11-28 16:05:59 +11001503named can restrict what a library using them can do.
Rob Pike992ce902017-11-28 16:05:59 +11001504</p>
1505
1506<p>
Rob Pike21672b32017-11-29 16:05:01 +11001507Here is an illustration of the difficulties.
1508Once one names a goroutine and constructs a model around
Rob Pike992ce902017-11-28 16:05:59 +11001509it, it becomes special, and one is tempted to associate all computation
1510with that goroutine, ignoring the possibility
1511of using multiple, possibly shared goroutines for the processing.
1512If the <code>net/http</code> package associated per-request
1513state with a goroutine,
1514clients would be unable to use more goroutines
1515when serving a request.
1516</p>
1517
1518<p>
Rob Pike21672b32017-11-29 16:05:01 +11001519Moreover, experience with libraries such as those for graphics systems
1520that require all processing to occur on the "main thread"
1521has shown how awkward and limiting the approach can be when
Rob Pike992ce902017-11-28 16:05:59 +11001522deployed in a concurrent language.
1523The very existence of a special thread or goroutine forces
1524the programmer to distort the program to avoid crashes
1525and other problems caused by inadvertently operating
1526on the wrong thread.
1527</p>
1528
1529<p>
1530For those cases where a particular goroutine is truly special,
1531the language provides features such as channels that can be
1532used in flexible ways to interact with it.
1533</p>
1534
Andrew Gerrand4164d602010-09-29 16:52:22 +10001535<h2 id="Functions_methods">Functions and Methods</h2>
1536
1537<h3 id="different_method_sets">
1538Why do T and *T have different method sets?</h3>
1539
1540<p>
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10001541From the <a href="/ref/spec#Types">Go Spec</a>:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001542</p>
1543
1544<blockquote>
1545The method set of any other named type <code>T</code> consists of all methods
1546with receiver type <code>T</code>. The method set of the corresponding pointer
1547type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
1548<code>T</code> (that is, it also contains the method set of <code>T</code>).
1549</blockquote>
1550
1551<p>
1552If an interface value contains a pointer <code>*T</code>,
1553a method call can obtain a value by dereferencing the pointer,
1554but if an interface value contains a value <code>T</code>,
1555there is no useful way for a method call to obtain a pointer.
1556</p>
1557
1558<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001559Even in cases where the compiler could take the address of a value
1560to pass to the method, if the method modifies the value the changes
1561will be lost in the caller.
Rob Pike694b2442015-06-29 13:27:41 +10001562As an example, if the <code>Write</code> method of
1563<a href="/pkg/bytes/#Buffer"><code>bytes.Buffer</code></a>
1564used a value receiver rather than a pointer,
1565this code:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001566</p>
1567
1568<pre>
1569var buf bytes.Buffer
1570io.Copy(buf, os.Stdin)
1571</pre>
1572
1573<p>
1574would copy standard input into a <i>copy</i> of <code>buf</code>,
1575not into <code>buf</code> itself.
1576This is almost never the desired behavior.
1577</p>
1578
1579<h3 id="closures_and_goroutines">
Rob Pikefcfed142012-01-23 08:39:53 -08001580What happens with closures running as goroutines?</h3>
Andrew Gerrand4164d602010-09-29 16:52:22 +10001581
1582<p>
1583Some confusion may arise when using closures with concurrency.
1584Consider the following program:
1585</p>
1586
1587<pre>
1588func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001589 done := make(chan bool)
Andrew Gerrand4164d602010-09-29 16:52:22 +10001590
Rob Pike5cff1902012-02-20 12:42:50 +11001591 values := []string{"a", "b", "c"}
Rob Pikefcfed142012-01-23 08:39:53 -08001592 for _, v := range values {
1593 go func() {
1594 fmt.Println(v)
1595 done &lt;- true
1596 }()
1597 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001598
Rob Pikefcfed142012-01-23 08:39:53 -08001599 // wait for all goroutines to complete before exiting
1600 for _ = range values {
Oling Cat018e89f2013-01-24 20:46:33 +11001601 &lt;-done
Rob Pikefcfed142012-01-23 08:39:53 -08001602 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001603}
1604</pre>
1605
1606<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001607One might mistakenly expect to see <code>a, b, c</code> as the output.
1608What you'll probably see instead is <code>c, c, c</code>. This is because
Rob Pikefcfed142012-01-23 08:39:53 -08001609each iteration of the loop uses the same instance of the variable <code>v</code>, so
Oling Cat018e89f2013-01-24 20:46:33 +11001610each closure shares that single variable. When the closure runs, it prints the
Rob Pikefcfed142012-01-23 08:39:53 -08001611value of <code>v</code> at the time <code>fmt.Println</code> is executed,
Oling Cat018e89f2013-01-24 20:46:33 +11001612but <code>v</code> may have been modified since the goroutine was launched.
Christian Himpel89ed40c2012-11-12 07:25:54 -08001613To help detect this and other problems before they happen, run
Dmitriy Vyukov2e1ddeb2014-05-07 18:49:13 +04001614<a href="/cmd/go/#hdr-Run_go_tool_vet_on_packages"><code>go vet</code></a>.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001615</p>
1616
1617<p>
Rob Pike0cab7d52012-09-07 09:11:39 -07001618To bind the current value of <code>v</code> to each closure as it is launched, one
1619must modify the inner loop to create a new variable each iteration.
1620One way is to pass the variable as an argument to the closure:
Andrew Gerrand4164d602010-09-29 16:52:22 +10001621</p>
1622
1623<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08001624 for _, v := range values {
1625 go func(<b>u</b> string) {
1626 fmt.Println(<b>u</b>)
1627 done &lt;- true
1628 }(<b>v</b>)
1629 }
Andrew Gerrand4164d602010-09-29 16:52:22 +10001630</pre>
1631
1632<p>
Oling Cat018e89f2013-01-24 20:46:33 +11001633In this example, the value of <code>v</code> is passed as an argument to the
Andrew Gerrand4164d602010-09-29 16:52:22 +10001634anonymous function. That value is then accessible inside the function as
1635the variable <code>u</code>.
1636</p>
1637
Rob Pike0cab7d52012-09-07 09:11:39 -07001638<p>
1639Even easier is just to create a new variable, using a declaration style that may
1640seem odd but works fine in Go:
1641</p>
1642
1643<pre>
1644 for _, v := range values {
1645 <b>v := v</b> // create a new 'v'.
1646 go func() {
1647 fmt.Println(<b>v</b>)
1648 done &lt;- true
1649 }()
1650 }
1651</pre>
1652
Andrew Gerrand4164d602010-09-29 16:52:22 +10001653<h2 id="Control_flow">Control flow</h2>
1654
1655<h3 id="Does_Go_have_a_ternary_form">
1656Does Go have the <code>?:</code> operator?</h3>
1657
1658<p>
Rob Pike694b2442015-06-29 13:27:41 +10001659There is no ternary testing operation in Go. You may use the following to achieve the same
Andrew Gerrand4164d602010-09-29 16:52:22 +10001660result:
1661</p>
1662
1663<pre>
1664if expr {
Rob Pikefcfed142012-01-23 08:39:53 -08001665 n = trueVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001666} else {
Rob Pikefcfed142012-01-23 08:39:53 -08001667 n = falseVal
Andrew Gerrand4164d602010-09-29 16:52:22 +10001668}
1669</pre>
1670
1671<h2 id="Packages_Testing">Packages and Testing</h2>
1672
1673<h3 id="How_do_I_create_a_multifile_package">
1674How do I create a multifile package?</h3>
1675
1676<p>
1677Put all the source files for the package in a directory by themselves.
1678Source files can refer to items from different files at will; there is
1679no need for forward declarations or a header file.
1680</p>
1681
1682<p>
1683Other than being split into multiple files, the package will compile and test
1684just like a single-file package.
1685</p>
1686
1687<h3 id="How_do_I_write_a_unit_test">
1688How do I write a unit test?</h3>
1689
1690<p>
1691Create a new file ending in <code>_test.go</code> in the same directory
1692as your package sources. Inside that file, <code>import "testing"</code>
1693and write functions of the form
1694</p>
1695
1696<pre>
1697func TestFoo(t *testing.T) {
1698 ...
1699}
1700</pre>
1701
1702<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001703Run <code>go test</code> in that directory.
Andrew Gerrand4164d602010-09-29 16:52:22 +10001704That script finds the <code>Test</code> functions,
1705builds a test binary, and runs it.
1706</p>
1707
Rob Pike5cff1902012-02-20 12:42:50 +11001708<p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
1709the <a href="/pkg/testing/"><code>testing</code></a> package
Andrew Gerrand399a36a2013-01-15 19:25:16 +11001710and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details.
Rob Pike5cff1902012-02-20 12:42:50 +11001711</p>
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10001712
Rob Pikef6615f12011-11-09 13:19:23 -08001713<h3 id="testing_framework">
1714Where is my favorite helper function for testing?</h3>
1715
1716<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001717Go'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 -08001718features provided in other language's testing frameworks such as assertion functions.
1719An <a href="#assertions">earlier section</a> of this document explained why Go
1720doesn't have assertions, and
1721the same arguments apply to the use of <code>assert</code> in tests.
1722Proper error handling means letting other tests run after one has failed, so
1723that the person debugging the failure gets a complete picture of what is
1724wrong. It is more useful for a test to report that
1725<code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
17262, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
1727answer for 2 and therefore no more tests were run. The programmer who
1728triggers the test failure may not be familiar with the code that fails.
1729Time invested writing a good error message now pays off later when the
1730test breaks.
1731</p>
1732
1733<p>
1734A related point is that testing frameworks tend to develop into mini-languages
1735of their own, with conditionals and controls and printing mechanisms,
1736but Go already has all those capabilities; why recreate them?
1737We'd rather write tests in Go; it's one fewer language to learn and the
1738approach keeps the tests straightforward and easy to understand.
1739</p>
1740
1741<p>
1742If the amount of extra code required to write
1743good errors seems repetitive and overwhelming, the test might work better if
1744table-driven, iterating over a list of inputs and outputs defined
1745in a data structure (Go has excellent support for data structure literals).
1746The work to write a good test and good error messages will then be amortized over many
1747test cases. The standard Go library is full of illustrative examples, such as in
Russ Cox220a6de2014-09-08 00:06:45 -04001748<a href="/src/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>.
Rob Pikef6615f12011-11-09 13:19:23 -08001749</p>
1750
Brad Fitzpatrick8a282422015-07-05 10:00:14 -07001751<h3 id="x_in_std">
1752Why isn't <i>X</i> in the standard library?</h3>
1753
1754<p>
1755The standard library's purpose is to support the runtime, connect to
1756the operating system, and provide key functionality that many Go
1757programs require, such as formatted I/O and networking.
1758It also contains elements important for web programming, including
1759cryptography and support for standards like HTTP, JSON, and XML.
1760</p>
1761
1762<p>
1763There is no clear criterion that defines what is included because for
1764a long time, this was the <i>only</i> Go library.
1765There are criteria that define what gets added today, however.
1766</p>
1767
1768<p>
1769New additions to the standard library are rare and the bar for
1770inclusion is high.
1771Code included in the standard library bears a large ongoing maintenance cost
1772(often borne by those other than the original author),
1773is subject to the <a href="/doc/go1compat.html">Go 1 compatibility promise</a>
1774(blocking fixes to any flaws in the API),
1775and is subject to the Go
1776<a href="https://golang.org/s/releasesched">release schedule</a>,
1777preventing bug fixes from being available to users quickly.
1778</p>
1779
1780<p>
1781Most new code should live outside of the standard library and be accessible
1782via the <a href="/cmd/go/"><code>go</code> tool</a>'s
1783<code>go get</code> command.
1784Such code can have its own maintainers, release cycle,
1785and compatibility guarantees.
1786Users can find packages and read their documentation at
1787<a href="https://godoc.org/">godoc.org</a>.
1788</p>
1789
1790<p>
1791Although there are pieces in the standard library that don't really belong,
1792such as <code>log/syslog</code>, we continue to maintain everything in the
1793library because of the Go 1 compatibility promise.
1794But we encourage most new code to live elsewhere.
1795</p>
Russ Cox32274452009-10-22 00:13:51 -07001796
1797<h2 id="Implementation">Implementation</h2>
1798
1799<h3 id="What_compiler_technology_is_used_to_build_the_compilers">
1800What compiler technology is used to build the compilers?</h3>
1801
1802<p>
Mike Rossetb4afe882013-03-12 17:12:56 -07001803<code>Gccgo</code> has a front end written in C++, with a recursive descent parser coupled to the
Brad Fitzpatrickdea6dab2016-08-18 15:50:30 +00001804standard GCC back end. <code>Gc</code> is written in Go with a recursive descent parser
Rob Pike694b2442015-06-29 13:27:41 +10001805and uses a custom loader, also written in Go but
1806based on the Plan 9 loader, to generate ELF/Mach-O/PE binaries.
Evan Shaw64d85762011-05-22 14:56:12 +10001807</p>
Russ Cox32274452009-10-22 00:13:51 -07001808
1809<p>
Rob Pike56c4d0a2014-09-27 11:56:54 -07001810We considered using LLVM for <code>gc</code> but we felt it was too large and
1811slow to meet our performance goals.
Evan Shaw64d85762011-05-22 14:56:12 +10001812</p>
Russ Cox32274452009-10-22 00:13:51 -07001813
1814<p>
Rob Pike694b2442015-06-29 13:27:41 +10001815The original <code>gc</code>, the Go compiler, was written in C
1816because of the difficulties of bootstrapping&mdash;you'd need a Go compiler to
1817set up a Go environment.
1818But things have advanced and as of Go 1.5 the compiler is written in Go.
1819It was converted from C to Go using automatic translation tools, as
1820described in <a href="/s/go13compiler">this design document</a>
1821and <a href="https://talks.golang.org/2015/gogo.slide#1">a recent talk</a>.
1822Thus the compiler is now "self-hosting", which means we must face
1823the bootstrapping problem.
1824The solution, naturally, is to have a working Go installation already,
1825just as one normally has a working C installation in place.
1826The story of how to bring up a new Go installation from source
1827is described <a href="/s/go15bootstrap">separately</a>.
Rob Pike56c4d0a2014-09-27 11:56:54 -07001828</p>
1829
1830<p>
Rob Pike694b2442015-06-29 13:27:41 +10001831Go is a fine language in which to implement a Go compiler.
1832Although <code>gc</code> does not use them (yet?), a native lexer and
1833parser are available in the <a href="/pkg/go/"><code>go</code></a> package
1834and there is also a <a href="/pkg/go/types">type checker</a>.
Evan Shaw64d85762011-05-22 14:56:12 +10001835</p>
Russ Cox32274452009-10-22 00:13:51 -07001836
Rob Pike966bf712011-03-01 13:54:22 -08001837<h3 id="How_is_the_run_time_support_implemented">
1838How is the run-time support implemented?</h3>
Russ Cox32274452009-10-22 00:13:51 -07001839
1840<p>
Rob Pike56c4d0a2014-09-27 11:56:54 -07001841Again due to bootstrapping issues, the run-time code was originally written mostly in C (with a
Rob Pike694b2442015-06-29 13:27:41 +10001842tiny bit of assembler) but it has since been translated to Go
1843(except for some assembler bits).
Rob Pike56c4d0a2014-09-27 11:56:54 -07001844<code>Gccgo</code>'s run-time support uses <code>glibc</code>.
Rob Pike694b2442015-06-29 13:27:41 +10001845The <code>gccgo</code> compiler implements goroutines using
1846a technique called segmented stacks,
Rob Pike287967f2014-03-21 13:59:30 +11001847supported by recent modifications to the gold linker.
Evan Shaw64d85762011-05-22 14:56:12 +10001848</p>
Andrew Gerrand08575732010-04-21 14:00:56 +10001849
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001850<h3 id="Why_is_my_trivial_program_such_a_large_binary">
1851Why is my trivial program such a large binary?</h3>
1852
1853<p>
Russ Coxb6c871a2018-01-09 15:26:21 -05001854The linker in the <code>gc</code> toolchain
Rob Pike694b2442015-06-29 13:27:41 +10001855creates statically-linked binaries by default. All Go binaries therefore include the Go
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001856run-time, along with the run-time type information necessary to support dynamic
1857type checks, reflection, and even panic-time stack traces.
Evan Shaw64d85762011-05-22 14:56:12 +10001858</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001859
1860<p>
Rob Pike0130a312012-03-07 15:29:26 +11001861A simple C "hello, world" program compiled and linked statically using gcc
1862on Linux is around 750 kB,
1863including an implementation of <code>printf</code>.
1864An equivalent Go program using <code>fmt.Printf</code>
Alexander Döringcdccd6a2016-10-23 16:03:38 +02001865is around 1.5 MB, but
Rob Pike56c4d0a2014-09-27 11:56:54 -07001866that includes more powerful run-time support and type information.
Evan Shaw64d85762011-05-22 14:56:12 +10001867</p>
Andrew Gerrand4b0ecd32011-03-01 21:35:46 +11001868
Rob Pike7d87f3d2011-08-06 11:21:59 +10001869<h3 id="unused_variables_and_imports">
1870Can I stop these complaints about my unused variable/import?</h3>
1871
1872<p>
1873The presence of an unused variable may indicate a bug, while
Rob Pikedba2faf2014-10-01 15:25:56 -07001874unused imports just slow down compilation,
1875an effect that can become substantial as a program accumulates
1876code and programmers over time.
1877For these reasons, Go refuses to compile programs with unused
1878variables or imports,
1879trading short-term convenience for long-term build speed and
1880program clarity.
Rob Pike7d87f3d2011-08-06 11:21:59 +10001881</p>
1882
1883<p>
Rob Pikedba2faf2014-10-01 15:25:56 -07001884Still, when developing code, it's common to create these situations
Rob Pike7d87f3d2011-08-06 11:21:59 +10001885temporarily and it can be annoying to have to edit them out before the
Oling Cat018e89f2013-01-24 20:46:33 +11001886program will compile.
Rob Pike7d87f3d2011-08-06 11:21:59 +10001887</p>
1888
1889<p>
1890Some have asked for a compiler option to turn those checks off
1891or at least reduce them to warnings.
1892Such an option has not been added, though,
1893because compiler options should not affect the semantics of the
1894language and because the Go compiler does not report warnings, only
1895errors that prevent compilation.
1896</p>
1897
1898<p>
1899There are two reasons for having no warnings. First, if it's worth
1900complaining about, it's worth fixing in the code. (And if it's not
1901worth fixing, it's not worth mentioning.) Second, having the compiler
1902generate warnings encourages the implementation to warn about weak
1903cases that can make compilation noisy, masking real errors that
1904<em>should</em> be fixed.
1905</p>
1906
1907<p>
1908It's easy to address the situation, though. Use the blank identifier
1909to let unused things persist while you're developing.
1910</p>
1911
1912<pre>
1913import "unused"
1914
1915// This declaration marks the import as used by referencing an
1916// item from the package.
1917var _ = unused.Item // TODO: Delete before committing!
1918
1919func main() {
Rob Pikefcfed142012-01-23 08:39:53 -08001920 debugData := debug.Profile()
1921 _ = debugData // Used only during debugging.
1922 ....
Rob Pike7d87f3d2011-08-06 11:21:59 +10001923}
1924</pre>
1925
Rob Pike56c4d0a2014-09-27 11:56:54 -07001926<p>
1927Nowadays, most Go programmers use a tool,
Andrew Gerrand7f0be1f2014-11-10 09:15:57 +11001928<a href="http://godoc.org/golang.org/x/tools/cmd/goimports">goimports</a>,
Rob Pike56c4d0a2014-09-27 11:56:54 -07001929which automatically rewrites a Go source file to have the correct imports,
1930eliminating the unused imports issue in practice.
1931This program is easily connected to most editors to run automatically when a Go source file is written.
1932</p>
1933
Andrew Gerrand08575732010-04-21 14:00:56 +10001934<h2 id="Performance">Performance</h2>
1935
1936<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
1937Why does Go perform badly on benchmark X?</h3>
1938
1939<p>
1940One of Go's design goals is to approach the performance of C for comparable
Oling Cat018e89f2013-01-24 20:46:33 +11001941programs, yet on some benchmarks it does quite poorly, including several
Shenghou Ma7a05fa82016-03-10 02:36:28 -05001942in <a href="https://go.googlesource.com/exp/+/master/shootout/">golang.org/x/exp/shootout</a>.
1943The slowest depend on libraries for which versions of comparable performance
1944are not available in Go.
1945For instance, <a href="https://go.googlesource.com/exp/+/master/shootout/pidigits.go">pidigits.go</a>
Rob Pikefcfed142012-01-23 08:39:53 -08001946depends on a multi-precision math package, and the C
Andrew Gerrand08575732010-04-21 14:00:56 +10001947versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
Oling Cat018e89f2013-01-24 20:46:33 +11001948written in optimized assembler).
Rob Pikefcfed142012-01-23 08:39:53 -08001949Benchmarks that depend on regular expressions
Shenghou Ma7a05fa82016-03-10 02:36:28 -05001950(<a href="https://go.googlesource.com/exp/+/master/shootout/regex-dna.go">regex-dna.go</a>,
1951for instance) are essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
Andrew Gerrand08575732010-04-21 14:00:56 +10001952mature, highly optimized regular expression libraries like PCRE.
1953</p>
1954
1955<p>
1956Benchmark games are won by extensive tuning and the Go versions of most
1957of the benchmarks need attention. If you measure comparable C
Rob Pikefcfed142012-01-23 08:39:53 -08001958and Go programs
Shenghou Ma7a05fa82016-03-10 02:36:28 -05001959(<a href="https://go.googlesource.com/exp/+/master/shootout/reverse-complement.go">reverse-complement.go</a>
1960is one example), you'll see the two languages are much closer in raw performance
1961than this suite would indicate.
Andrew Gerrand08575732010-04-21 14:00:56 +10001962</p>
1963
1964<p>
1965Still, there is room for improvement. The compilers are good but could be
Andrew Gerrand05427742010-04-23 10:02:10 +10001966better, many libraries need major performance work, and the garbage collector
Oling Cat018e89f2013-01-24 20:46:33 +11001967isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
Rob Pikefcfed142012-01-23 08:39:53 -08001968garbage can have a huge effect.)
Andrew Gerrand08575732010-04-21 14:00:56 +10001969</p>
1970
Rob Pike93c4a242011-08-06 07:41:55 +10001971<p>
Rob Pike5cff1902012-02-20 12:42:50 +11001972In any case, Go can often be very competitive.
1973There has been significant improvement in the performance of many programs
1974as the language and tools have developed.
1975See the blog post about
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10001976<a href="//blog.golang.org/2011/06/profiling-go-programs.html">profiling
Rob Pike93c4a242011-08-06 07:41:55 +10001977Go programs</a> for an informative example.
1978
Andrew Gerrand4164d602010-09-29 16:52:22 +10001979<h2 id="change_from_c">Changes from C</h2>
1980
1981<h3 id="different_syntax">
1982Why is the syntax so different from C?</h3>
1983<p>
1984Other than declaration syntax, the differences are not major and stem
1985from two desires. First, the syntax should feel light, without too
1986many mandatory keywords, repetition, or arcana. Second, the language
1987has been designed to be easy to analyze
1988and can be parsed without a symbol table. This makes it much easier
1989to build tools such as debuggers, dependency analyzers, automated
1990documentation extractors, IDE plug-ins, and so on. C and its
1991descendants are notoriously difficult in this regard.
1992</p>
1993
1994<h3 id="declarations_backwards">
1995Why are declarations backwards?</h3>
1996<p>
1997They're only backwards if you're used to C. In C, the notion is that a
1998variable is declared like an expression denoting its type, which is a
1999nice idea, but the type and expression grammars don't mix very well and
2000the results can be confusing; consider function pointers. Go mostly
2001separates expression and type syntax and that simplifies things (using
2002prefix <code>*</code> for pointers is an exception that proves the rule). In C,
2003the declaration
2004</p>
2005<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08002006 int* a, b;
Andrew Gerrand4164d602010-09-29 16:52:22 +10002007</pre>
2008<p>
2009declares <code>a</code> to be a pointer but not <code>b</code>; in Go
2010</p>
2011<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08002012 var a, b *int
Andrew Gerrand4164d602010-09-29 16:52:22 +10002013</pre>
2014<p>
2015declares both to be pointers. This is clearer and more regular.
2016Also, the <code>:=</code> short declaration form argues that a full variable
2017declaration should present the same order as <code>:=</code> so
2018</p>
2019<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08002020 var a uint64 = 1
Andrew Gerrand4164d602010-09-29 16:52:22 +10002021</pre>
Stefan Nilssonc50074e2012-02-29 15:07:52 -08002022<p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10002023has the same effect as
Stefan Nilssonc50074e2012-02-29 15:07:52 -08002024</p>
Andrew Gerrand4164d602010-09-29 16:52:22 +10002025<pre>
Rob Pikefcfed142012-01-23 08:39:53 -08002026 a := uint64(1)
Andrew Gerrand4164d602010-09-29 16:52:22 +10002027</pre>
2028<p>
2029Parsing is also simplified by having a distinct grammar for types that
2030is not just the expression grammar; keywords such as <code>func</code>
2031and <code>chan</code> keep things clear.
2032</p>
2033
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10002034<p>
Rob Pike93c4a242011-08-06 07:41:55 +10002035See the article about
Francisco Souza6033a482012-03-13 14:46:08 +11002036<a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
Rob Pike93c4a242011-08-06 07:41:55 +10002037for more details.
Andrew Gerrand5ec55c52010-09-30 11:23:39 +10002038</p>
2039
Andrew Gerrand4164d602010-09-29 16:52:22 +10002040<h3 id="no_pointer_arithmetic">
2041Why is there no pointer arithmetic?</h3>
2042<p>
2043Safety. Without pointer arithmetic it's possible to create a
2044language that can never derive an illegal address that succeeds
2045incorrectly. Compiler and hardware technology have advanced to the
2046point where a loop using array indices can be as efficient as a loop
2047using pointer arithmetic. Also, the lack of pointer arithmetic can
2048simplify the implementation of the garbage collector.
2049</p>
2050
2051<h3 id="inc_dec">
2052Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3>
2053<p>
2054Without pointer arithmetic, the convenience value of pre- and postfix
2055increment operators drops. By removing them from the expression
2056hierarchy altogether, expression syntax is simplified and the messy
2057issues around order of evaluation of <code>++</code> and <code>--</code>
2058(consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
2059are eliminated as well. The simplification is
2060significant. As for postfix vs. prefix, either would work fine but
2061the postfix version is more traditional; insistence on prefix arose
2062with the STL, a library for a language whose name contains, ironically, a
2063postfix increment.
2064</p>
2065
2066<h3 id="semicolons">
2067Why are there braces but no semicolons? And why can't I put the opening
2068brace on the next line?</h3>
2069<p>
2070Go uses brace brackets for statement grouping, a syntax familiar to
2071programmers who have worked with any language in the C family.
2072Semicolons, however, are for parsers, not for people, and we wanted to
2073eliminate them as much as possible. To achieve this goal, Go borrows
2074a trick from BCPL: the semicolons that separate statements are in the
2075formal grammar but are injected automatically, without lookahead, by
2076the lexer at the end of any line that could be the end of a statement.
2077This works very well in practice but has the effect that it forces a
2078brace style. For instance, the opening brace of a function cannot
2079appear on a line by itself.
2080</p>
Evan Shaw64d85762011-05-22 14:56:12 +10002081
Andrew Gerrand4164d602010-09-29 16:52:22 +10002082<p>
2083Some have argued that the lexer should do lookahead to permit the
2084brace to live on the next line. We disagree. Since Go code is meant
2085to be formatted automatically by
Shenghou Ma97b13ac2012-03-07 08:15:47 +11002086<a href="/cmd/gofmt/"><code>gofmt</code></a>,
Andrew Gerrand4164d602010-09-29 16:52:22 +10002087<i>some</i> style must be chosen. That style may differ from what
2088you've used in C or Java, but Go is a new language and
2089<code>gofmt</code>'s style is as good as any other. More
2090important&mdash;much more important&mdash;the advantages of a single,
2091programmatically mandated format for all Go programs greatly outweigh
2092any perceived disadvantages of the particular style.
2093Note too that Go's style means that an interactive implementation of
2094Go can use the standard syntax one line at a time without special rules.
2095</p>
2096
2097<h3 id="garbage_collection">
2098Why do garbage collection? Won't it be too expensive?</h3>
2099<p>
2100One of the biggest sources of bookkeeping in systems programs is
2101memory management. We feel it's critical to eliminate that
2102programmer overhead, and advances in garbage collection
2103technology in the last few years give us confidence that we can
2104implement it with low enough overhead and no significant
Rob Pikefcfed142012-01-23 08:39:53 -08002105latency.
Andrew Gerrand4164d602010-09-29 16:52:22 +10002106</p>
Evan Shaw64d85762011-05-22 14:56:12 +10002107
Andrew Gerrand4164d602010-09-29 16:52:22 +10002108<p>
2109Another point is that a large part of the difficulty of concurrent
2110and multi-threaded programming is memory management;
2111as objects get passed among threads it becomes cumbersome
2112to guarantee they become freed safely.
2113Automatic garbage collection makes concurrent code far easier to write.
2114Of course, implementing garbage collection in a concurrent environment is
2115itself a challenge, but meeting it once rather than in every
2116program helps everyone.
2117</p>
Evan Shaw64d85762011-05-22 14:56:12 +10002118
Andrew Gerrand4164d602010-09-29 16:52:22 +10002119<p>
2120Finally, concurrency aside, garbage collection makes interfaces
2121simpler because they don't need to specify how memory is managed across them.
2122</p>
Rob Pike93c4a242011-08-06 07:41:55 +10002123
2124<p>
Rob Pike694b2442015-06-29 13:27:41 +10002125The current implementation is a parallel mark-and-sweep collector.
2126Recent improvements, documented in
2127<a href="/s/go14gc">this design document</a>,
2128have introduced bounded pause times and improved the
2129parallelism.
2130Future versions might attempt new approaches.
Rob Pikefcfed142012-01-23 08:39:53 -08002131</p>
2132
2133<p>
Rob Pike93c4a242011-08-06 07:41:55 +10002134On the topic of performance, keep in mind that Go gives the programmer
2135considerable control over memory layout and allocation, much more than
2136is typical in garbage-collected languages. A careful programmer can reduce
2137the garbage collection overhead dramatically by using the language well;
2138see the article about
Andrew Gerrand43ad89d2014-07-25 10:28:39 +10002139<a href="//blog.golang.org/2011/06/profiling-go-programs.html">profiling
Rob Pike93c4a242011-08-06 07:41:55 +10002140Go programs</a> for a worked example, including a demonstration of Go's
2141profiling tools.
2142</p>