github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/doc/go_faq.html (about)

     1  <!--{
     2  	"Title": "Frequently Asked Questions (FAQ)",
     3  	"Path": "/doc/faq"
     4  }-->
     5  
     6  <h2 id="Origins">Origins</h2>
     7  
     8  <h3 id="What_is_the_purpose_of_the_project">
     9  What is the purpose of the project?</h3>
    10  
    11  <p>
    12  No major systems language has emerged in over a decade, but over that time
    13  the computing landscape has changed tremendously. There are several trends:
    14  </p>
    15  
    16  <ul>
    17  <li>
    18  Computers are enormously quicker but software development is not faster.
    19  <li>
    20  Dependency management is a big part of software development today but the
    21  &ldquo;header files&rdquo; of languages in the C tradition are antithetical to clean
    22  dependency analysis&mdash;and fast compilation.
    23  <li>
    24  There is a growing rebellion against cumbersome type systems like those of
    25  Java and C++, pushing people towards dynamically typed languages such as
    26  Python and JavaScript.
    27  <li>
    28  Some fundamental concepts such as garbage collection and parallel computation
    29  are not well supported by popular systems languages.
    30  <li>
    31  The emergence of multicore computers has generated worry and confusion.
    32  </ul>
    33  
    34  <p>
    35  We believe it's worth trying again with a new language, a concurrent,
    36  garbage-collected language with fast compilation. Regarding the points above:
    37  </p>
    38  
    39  <ul>
    40  <li>
    41  It is possible to compile a large Go program in a few seconds on a single computer.
    42  <li>
    43  Go provides a model for software construction that makes dependency
    44  analysis easy and avoids much of the overhead of C-style include files and
    45  libraries.
    46  <li>
    47  Go's type system has no hierarchy, so no time is spent defining the
    48  relationships between types. Also, although Go has static types the language
    49  attempts to make types feel lighter weight than in typical OO languages.
    50  <li>
    51  Go is fully garbage-collected and provides fundamental support for
    52  concurrent execution and communication.
    53  <li>
    54  By its design, Go proposes an approach for the construction of system
    55  software on multicore machines.
    56  </ul>
    57  
    58  <p>
    59  A much more expansive answer to this question is available in the article,
    60  <a href="http://talks.golang.org/2012/splash.article">Go at Google:
    61  Language Design in the Service of Software Engineering</a>.
    62  
    63  <h3 id="What_is_the_status_of_the_project">
    64  What is the status of the project?</h3>
    65  
    66  <p>
    67  Go became a public open source project on November 10, 2009.
    68  After a couple of years of very active design and development, stability was called for and
    69  Go 1 was <a href="http://blog.golang.org/2012/03/go-version-1-is-released.html">released</a>
    70  on March 28, 2012.
    71  Go 1, which includes a <a href="/ref/spec">language specification</a>,
    72  <a href="/pkg/">standard libraries</a>,
    73  and <a href="/cmd/go/">custom tools</a>,
    74  provides a stable foundation for creating reliable products, projects, and publications.
    75  </p>
    76  
    77  <p>
    78  With that stability established, we are using Go to develop programs, products, and tools rather than
    79  actively changing the language and libraries.
    80  In fact, the purpose of Go 1 is to provide <a href="/doc/go1compat.html">long-term stability</a>.
    81  Backwards-incompatible changes will not be made to any Go 1 point release.
    82  We want to use what we have to learn how a future version of Go might look, rather than to play with
    83  the language underfoot.
    84  </p>
    85  
    86  <p>
    87  Of course, development will continue on Go itself, but the focus will be on performance, reliability,
    88  portability and the addition of new functionality such as improved support for internationalization.
    89  </p>
    90  
    91  <p>
    92  There 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  
    95  <h3 id="What_is_the_origin_of_the_name">
    96  What is the origin of the name?</h3>
    97  
    98  <p>
    99  &ldquo;Ogle&rdquo; would be a good name for a Go debugger.
   100  </p>
   101  
   102  <h3 id="Whats_the_origin_of_the_mascot">
   103  What's the origin of the mascot?</h3>
   104  
   105  <p>
   106  The mascot and logo were designed by
   107  <a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
   108  <a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
   109  the Plan 9 bunny.
   110  The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
   111  T-shirt design some years ago.
   112  The logo and mascot are covered by the
   113  <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
   114  license.
   115  </p>
   116  
   117  <h3 id="history">
   118  What is the history of the project?</h3>
   119  <p>
   120  Robert Griesemer, Rob Pike and Ken Thompson started sketching the
   121  goals for a new language on the white board on September 21, 2007.
   122  Within a few days the goals had settled into a plan to do something
   123  and a fair idea of what it would be.  Design continued part-time in
   124  parallel with unrelated work.  By January 2008, Ken had started work
   125  on a compiler with which to explore ideas; it generated C code as its
   126  output.  By mid-year the language had become a full-time project and
   127  had settled enough to attempt a production compiler.  In May 2008,
   128  Ian Taylor independently started on a GCC front end for Go using the
   129  draft specification.  Russ Cox joined in late 2008 and helped move the language
   130  and libraries from prototype to reality.
   131  </p>
   132  
   133  <p>
   134  Go became a public open source project on November 10, 2009.
   135  Many people from the community have contributed ideas, discussions, and code.
   136  </p>
   137  
   138  <h3 id="creating_a_new_language">
   139  Why are you creating a new language?</h3>
   140  <p>
   141  Go was born out of frustration with existing languages and
   142  environments for systems programming.  Programming had become too
   143  difficult and the choice of languages was partly to blame.  One had to
   144  choose either efficient compilation, efficient execution, or ease of
   145  programming; all three were not available in the same mainstream
   146  language.  Programmers who could were choosing ease over
   147  safety and efficiency by moving to dynamically typed languages such as
   148  Python and JavaScript rather than C++ or, to a lesser extent, Java.
   149  </p>
   150  
   151  <p>
   152  Go is an attempt to combine the ease of programming of an interpreted,
   153  dynamically typed
   154  language with the efficiency and safety of a statically typed, compiled language.
   155  It also aims to be modern, with support for networked and multicore
   156  computing.  Finally, it is intended to be <i>fast</i>: it should take
   157  at most a few seconds to build a large executable on a single computer.
   158  To meet these goals required addressing a number of
   159  linguistic issues: an expressive but lightweight type system;
   160  concurrency and garbage collection; rigid dependency specification;
   161  and so on.  These cannot be addressed well by libraries or tools; a new
   162  language was called for.
   163  </p>
   164  
   165  <p>
   166  The article <a href="http://talks.golang.org/2012/splash.article">Go at Google</a>
   167  discusses the background and motivation behind the design of the Go language,
   168  as well as providing more detail about many of the answers presented in this FAQ.
   169  </p>
   170  
   171  <h3 id="ancestors">
   172  What are Go's ancestors?</h3>
   173  <p>
   174  Go is mostly in the C family (basic syntax),
   175  with significant input from the Pascal/Modula/Oberon
   176  family (declarations, packages),
   177  plus some ideas from languages
   178  inspired by Tony Hoare's CSP,
   179  such as Newsqueak and Limbo (concurrency).
   180  However, it is a new language across the board.
   181  In every respect the language was designed by thinking
   182  about what programmers do and how to make programming, at least the
   183  kind of programming we do, more effective, which means more fun.
   184  </p>
   185  
   186  <h3 id="principles">
   187  What are the guiding principles in the design?</h3>
   188  <p>
   189  Programming today involves too much bookkeeping, repetition, and
   190  clerical work.  As Dick Gabriel says, &ldquo;Old programs read
   191  like quiet conversations between a well-spoken research worker and a
   192  well-studied mechanical colleague, not as a debate with a compiler.
   193  Who'd have guessed sophistication bought such noise?&rdquo;
   194  The sophistication is worthwhile&mdash;no one wants to go back to
   195  the old languages&mdash;but can it be more quietly achieved?
   196  </p>
   197  <p>
   198  Go attempts to reduce the amount of typing in both senses of the word.
   199  Throughout its design, we have tried to reduce clutter and
   200  complexity.  There are no forward declarations and no header files;
   201  everything is declared exactly once.  Initialization is expressive,
   202  automatic, and easy to use.  Syntax is clean and light on keywords.
   203  Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
   204  simple type derivation using the <code>:=</code>
   205  declare-and-initialize construct.  And perhaps most radically, there
   206  is no type hierarchy: types just <i>are</i>, they don't have to
   207  announce their relationships.  These simplifications allow Go to be
   208  expressive yet comprehensible without sacrificing, well, sophistication.
   209  </p>
   210  <p>
   211  Another important principle is to keep the concepts orthogonal.
   212  Methods can be implemented for any type; structures represent data while
   213  interfaces represent abstraction; and so on.  Orthogonality makes it
   214  easier to understand what happens when things combine.
   215  </p>
   216  
   217  <h2 id="Usage">Usage</h2>
   218  
   219  <h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
   220  
   221  <p>
   222  Yes. There are now several Go programs deployed in
   223  production inside Google.  A public example is the server behind
   224  <a href="http://golang.org">http://golang.org</a>.
   225  It's just the <a href="/cmd/godoc"><code>godoc</code></a>
   226  document server running in a production configuration on
   227  <a href="https://developers.google.com/appengine/">Google App Engine</a>.
   228  </p>
   229  
   230  <p>
   231  Other examples include the <a href="https://code.google.com/p/vitess/">Vitess</a>
   232  system for large-scale SQL installations and Google's download server, <code>dl.google.com</code>,
   233  which delivers Chrome binaries and other large installables such as <code>apt-get</code>
   234  packages.
   235  </p>
   236  
   237  <h3 id="Do_Go_programs_link_with_Cpp_programs">
   238  Do Go programs link with C/C++ programs?</h3>
   239  
   240  <p>
   241  There are two Go compiler implementations, <code>gc</code>
   242  (the <code>6g</code> program and friends) and <code>gccgo</code>.
   243  <code>Gc</code> uses a different calling convention and linker and can
   244  therefore only be linked with C programs using the same convention.
   245  There is such a C compiler but no C++ compiler.
   246  <code>Gccgo</code> is a GCC front-end that can, with care, be linked with
   247  GCC-compiled C or C++ programs.
   248  </p>
   249  
   250  <p>
   251  The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
   252  &ldquo;foreign function interface&rdquo; to allow safe calling of
   253  C libraries from Go code. SWIG extends this capability to C++ libraries.
   254  </p>
   255  
   256  
   257  <h3 id="Does_Go_support_Google_protocol_buffers">
   258  Does Go support Google's protocol buffers?</h3>
   259  
   260  <p>
   261  A separate open source project provides the necessary compiler plugin and library.
   262  It is available at
   263  <a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
   264  </p>
   265  
   266  
   267  <h3 id="Can_I_translate_the_Go_home_page">
   268  Can I translate the Go home page into another language?</h3>
   269  
   270  <p>
   271  Absolutely. We encourage developers to make Go Language sites in their own languages.
   272  However, if you choose to add the Google logo or branding to your site
   273  (it does not appear on <a href="http://golang.org/">golang.org</a>),
   274  you will need to abide by the guidelines at
   275  <a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
   276  </p>
   277  
   278  <h2 id="Design">Design</h2>
   279  
   280  <h3 id="unicode_identifiers">
   281  What's up with Unicode identifiers?</h3>
   282  
   283  <p>
   284  It was important to us to extend the space of identifiers from the
   285  confines of ASCII.  Go's rule&mdash;identifier characters must be
   286  letters or digits as defined by Unicode&mdash;is simple to understand
   287  and to implement but has restrictions.  Combining characters are
   288  excluded by design, for instance.
   289  Until there
   290  is an agreed external definition of what an identifier might be,
   291  plus a definition of canonicalization of identifiers that guarantees
   292  no ambiguity, it seemed better to keep combining characters out of
   293  the mix.  Thus we have a simple rule that can be expanded later
   294  without breaking programs, one that avoids bugs that would surely arise
   295  from a rule that admits ambiguous identifiers.
   296  </p>
   297  
   298  <p>
   299  On a related note, since an exported identifier must begin with an
   300  upper-case letter, identifiers created from &ldquo;letters&rdquo;
   301  in some languages can, by definition, not be exported.  For now the
   302  only solution is to use something like <code>X日本語</code>, which
   303  is clearly unsatisfactory; we are considering other options.  The
   304  case-for-visibility rule is unlikely to change however; it's one
   305  of our favorite features of Go.
   306  </p>
   307  
   308  <h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
   309  
   310  <p>
   311  Every language contains novel features and omits someone's favorite
   312  feature. Go was designed with an eye on felicity of programming, speed of
   313  compilation, orthogonality of concepts, and the need to support features
   314  such as concurrency and garbage collection. Your favorite feature may be
   315  missing because it doesn't fit, because it affects compilation speed or
   316  clarity of design, or because it would make the fundamental system model
   317  too difficult.
   318  </p>
   319  
   320  <p>
   321  If it bothers you that Go is missing feature <var>X</var>,
   322  please forgive us and investigate the features that Go does have. You might find that
   323  they compensate in interesting ways for the lack of <var>X</var>.
   324  </p>
   325  
   326  <h3 id="generics">
   327  Why does Go not have generic types?</h3>
   328  <p>
   329  Generics may well be added at some point.  We don't feel an urgency for
   330  them, although we understand some programmers do.
   331  </p>
   332  
   333  <p>
   334  Generics are convenient but they come at a cost in
   335  complexity in the type system and run-time.  We haven't yet found a
   336  design that gives value proportionate to the complexity, although we
   337  continue to think about it.  Meanwhile, Go's built-in maps and slices,
   338  plus the ability to use the empty interface to construct containers
   339  (with explicit unboxing) mean in many cases it is possible to write
   340  code that does what generics would enable, if less smoothly.
   341  </p>
   342  
   343  <p>
   344  This remains an open issue.
   345  </p>
   346  
   347  <h3 id="exceptions">
   348  Why does Go not have exceptions?</h3>
   349  <p>
   350  We believe that coupling exceptions to a control
   351  structure, as in the <code>try-catch-finally</code> idiom, results in
   352  convoluted code.  It also tends to encourage programmers to label
   353  too many ordinary errors, such as failing to open a file, as
   354  exceptional.
   355  </p>
   356  
   357  <p>
   358  Go takes a different approach.  For plain error handling, Go's multi-value
   359  returns make it easy to report an error without overloading the return value.
   360  <a href="/doc/articles/error_handling.html">A canonical error type, coupled
   361  with Go's other features</a>, makes error handling pleasant but quite different
   362  from that in other languages.
   363  </p>
   364  
   365  <p>
   366  Go also has a couple
   367  of built-in functions to signal and recover from truly exceptional
   368  conditions.  The recovery mechanism is executed only as part of a
   369  function's state being torn down after an error, which is sufficient
   370  to handle catastrophe but requires no extra control structures and,
   371  when used well, can result in clean error-handling code.
   372  </p>
   373  
   374  <p>
   375  See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
   376  </p>
   377  
   378  <h3 id="assertions">
   379  Why does Go not have assertions?</h3>
   380  
   381  <p>
   382  Go doesn't provide assertions. They are undeniably convenient, but our
   383  experience has been that programmers use them as a crutch to avoid thinking
   384  about proper error handling and reporting. Proper error handling means that
   385  servers continue operation after non-fatal errors instead of crashing.
   386  Proper error reporting means that errors are direct and to the point,
   387  saving the programmer from interpreting a large crash trace. Precise
   388  errors are particularly important when the programmer seeing the errors is
   389  not familiar with the code.
   390  </p>
   391  
   392  <p>
   393  We understand that this is a point of contention. There are many things in
   394  the Go language and libraries that differ from modern practices, simply
   395  because we feel it's sometimes worth trying a different approach.
   396  </p>
   397  
   398  <h3 id="csp">
   399  Why build concurrency on the ideas of CSP?</h3>
   400  <p>
   401  Concurrency and multi-threaded programming have a reputation
   402  for difficulty.  We believe this is due partly to complex
   403  designs such as pthreads and partly to overemphasis on low-level details
   404  such as mutexes, condition variables, and memory barriers.
   405  Higher-level interfaces enable much simpler code, even if there are still
   406  mutexes and such under the covers.
   407  </p>
   408  
   409  <p>
   410  One of the most successful models for providing high-level linguistic support
   411  for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
   412  Occam and Erlang are two well known languages that stem from CSP.
   413  Go's concurrency primitives derive from a different part of the family tree
   414  whose main contribution is the powerful notion of channels as first class objects.
   415  Experience with several earlier languages has shown that the CSP model
   416  fits well into a procedural language framework.
   417  </p>
   418  
   419  <h3 id="goroutines">
   420  Why goroutines instead of threads?</h3>
   421  <p>
   422  Goroutines are part of making concurrency easy to use.  The idea, which has
   423  been around for a while, is to multiplex independently executing
   424  functions&mdash;coroutines&mdash;onto a set of threads.
   425  When a coroutine blocks, such as by calling a blocking system call,
   426  the run-time automatically moves other coroutines on the same operating
   427  system thread to a different, runnable thread so they won't be blocked.
   428  The programmer sees none of this, which is the point.
   429  The result, which we call goroutines, can be very cheap: unless they spend a lot of time
   430  in long-running system calls, they cost little more than the memory
   431  for the stack, which is just a few kilobytes.
   432  </p>
   433  
   434  <p>
   435  To make the stacks small, Go's run-time uses segmented stacks.  A newly
   436  minted goroutine is given a few kilobytes, which is almost always enough.
   437  When it isn't, the run-time allocates (and frees) extension segments automatically.
   438  The overhead averages about three cheap instructions per function call.
   439  It is practical to create hundreds of thousands of goroutines in the same
   440  address space.  If goroutines were just threads, system resources would
   441  run out at a much smaller number.
   442  </p>
   443  
   444  <h3 id="atomic_maps">
   445  Why are map operations not defined to be atomic?</h3>
   446  
   447  <p>
   448  After long discussion it was decided that the typical use of maps did not require
   449  safe access from multiple threads, and in those cases where it did, the map was
   450  probably part of some larger data structure or computation that was already
   451  synchronized.  Therefore requiring that all map operations grab a mutex would slow
   452  down most programs and add safety to few.  This was not an easy decision,
   453  however, since it means uncontrolled map access can crash the program.
   454  </p>
   455  
   456  <p>
   457  The language does not preclude atomic map updates.  When required, such
   458  as when hosting an untrusted program, the implementation could interlock
   459  map access.
   460  </p>
   461  
   462  <h3 id="language_changes">
   463  Will you accept my language change?</h3>
   464  
   465  <p>
   466  People often suggest improvements to the language—the
   467  <a href="http://groups.google.com/group/golang-nuts">mailing list</a>
   468  contains a rich history of such discussions—but very few of these changes have
   469  been accepted.
   470  </p>
   471  
   472  <p>
   473  Although Go is an open source project, the language and libraries are protected
   474  by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents
   475  changes that break existing programs.
   476  If your proposal violates the Go 1 specification we cannot even entertain the
   477  idea, regardless of its merit.
   478  A future major release of Go may be incompatible with Go 1, but we're not ready
   479  to start talking about what that might be.
   480  </p>
   481  
   482  <p>
   483  Even if your proposal is compatible with the Go 1 spec, it might
   484  not be in the spirit of Go's design goals.
   485  The article <i><a href="http://talks.golang.org/2012/splash.article">Go
   486  at Google: Language Design in the Service of Software Engineering</a></i>
   487  explains Go's origins and the motivation behind its design.
   488  </p>
   489  
   490  <h2 id="types">Types</h2>
   491  
   492  <h3 id="Is_Go_an_object-oriented_language">
   493  Is Go an object-oriented language?</h3>
   494  
   495  <p>
   496  Yes and no. Although Go has types and methods and allows an
   497  object-oriented style of programming, there is no type hierarchy.
   498  The concept of &ldquo;interface&rdquo; in Go provides a different approach that
   499  we believe is easy to use and in some ways more general. There are
   500  also ways to embed types in other types to provide something
   501  analogous&mdash;but not identical&mdash;to subclassing.
   502  Moreover, methods in Go are more general than in C++ or Java:
   503  they can be defined for any sort of data, even built-in types such
   504  as plain, &ldquo;unboxed&rdquo; integers.
   505  They are not restricted to structs (classes).
   506  </p>
   507  
   508  <p>
   509  Also, the lack of type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
   510  lightweight than in languages such as C++ or Java.
   511  </p>
   512  
   513  <h3 id="How_do_I_get_dynamic_dispatch_of_methods">
   514  How do I get dynamic dispatch of methods?</h3>
   515  
   516  <p>
   517  The only way to have dynamically dispatched methods is through an
   518  interface. Methods on a struct or any other concrete type are always resolved statically.
   519  </p>
   520  
   521  <h3 id="inheritance">
   522  Why is there no type inheritance?</h3>
   523  <p>
   524  Object-oriented programming, at least in the best-known languages,
   525  involves too much discussion of the relationships between types,
   526  relationships that often could be derived automatically.  Go takes a
   527  different approach.
   528  </p>
   529  
   530  <p>
   531  Rather than requiring the programmer to declare ahead of time that two
   532  types are related, in Go a type automatically satisfies any interface
   533  that specifies a subset of its methods.  Besides reducing the
   534  bookkeeping, this approach has real advantages.  Types can satisfy
   535  many interfaces at once, without the complexities of traditional
   536  multiple inheritance.
   537  Interfaces can be very lightweight&mdash;an interface with
   538  one or even zero methods can express a useful concept.
   539  Interfaces can be added after the fact if a new idea comes along
   540  or for testing&mdash;without annotating the original types.
   541  Because there are no explicit relationships between types
   542  and interfaces, there is no type hierarchy to manage or discuss.
   543  </p>
   544  
   545  <p>
   546  It's possible to use these ideas to construct something analogous to
   547  type-safe Unix pipes.  For instance, see how <code>fmt.Fprintf</code>
   548  enables formatted printing to any output, not just a file, or how the
   549  <code>bufio</code> package can be completely separate from file I/O,
   550  or how the <code>image</code> packages generate compressed
   551  image files.  All these ideas stem from a single interface
   552  (<code>io.Writer</code>) representing a single method
   553  (<code>Write</code>).  And that's only scratching the surface.
   554  Go's interfaces have a profound influence on how programs are structured.
   555  </p>
   556  
   557  <p>
   558  It takes some getting used to but this implicit style of type
   559  dependency is one of the most productive things about Go.
   560  </p>
   561  
   562  <h3 id="methods_on_basics">
   563  Why is <code>len</code> a function and not a method?</h3>
   564  <p>
   565  We debated this issue but decided
   566  implementing <code>len</code> and friends as functions was fine in practice and
   567  didn't complicate questions about the interface (in the Go type sense)
   568  of basic types.
   569  </p>
   570  
   571  <h3 id="overloading">
   572  Why does Go not support overloading of methods and operators?</h3>
   573  <p>
   574  Method dispatch is simplified if it doesn't need to do type matching as well.
   575  Experience with other languages told us that having a variety of
   576  methods with the same name but different signatures was occasionally useful
   577  but that it could also be confusing and fragile in practice.  Matching only by name
   578  and requiring consistency in the types was a major simplifying decision
   579  in Go's type system.
   580  </p>
   581  
   582  <p>
   583  Regarding operator overloading, it seems more a convenience than an absolute
   584  requirement.  Again, things are simpler without it.
   585  </p>
   586  
   587  <h3 id="implements_interface">
   588  Why doesn't Go have "implements" declarations?</h3>
   589  
   590  <p>
   591  A Go type satisfies an interface by implementing the methods of that interface,
   592  nothing more.  This property allows interfaces to be defined and used without
   593  having to modify existing code.  It enables a kind of structural typing that
   594  promotes separation of concerns and improves code re-use, and makes it easier
   595  to build on patterns that emerge as the code develops.
   596  The semantics of interfaces is one of the main reasons for Go's nimble,
   597  lightweight feel.
   598  </p>
   599  
   600  <p>
   601  See the <a href="#inheritance">question on type inheritance</a> for more detail.
   602  </p>
   603  
   604  <h3 id="guarantee_satisfies_interface">
   605  How can I guarantee my type satisfies an interface?</h3>
   606  
   607  <p>
   608  You can ask the compiler to check that the type <code>T</code> implements the
   609  interface <code>I</code> by attempting an assignment:
   610  </p>
   611  
   612  <pre>
   613  type T struct{}
   614  var _ I = T{}   // Verify that T implements I.
   615  </pre>
   616  
   617  <p>
   618  If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
   619  at compile time.
   620  </p>
   621  
   622  <p>
   623  If you wish the users of an interface to explicitly declare that they implement
   624  it, you can add a method with a descriptive name to the interface's method set.
   625  For example:
   626  </p>
   627  
   628  <pre>
   629  type Fooer interface {
   630      Foo()
   631      ImplementsFooer()
   632  }
   633  </pre>
   634  
   635  <p>
   636  A type must then implement the <code>ImplementsFooer</code> method to be a
   637  <code>Fooer</code>, clearly documenting the fact and announcing it in
   638  <a href="/cmd/godoc/">godoc</a>'s output.
   639  </p>
   640  
   641  <pre>
   642  type Bar struct{}
   643  func (b Bar) ImplementsFooer() {}
   644  func (b Bar) Foo() {}
   645  </pre>
   646  
   647  <p>
   648  Most code doesn't make use of such constraints, since they limit the utility of
   649  the interface idea. Sometimes, though, they're necessary to resolve ambiguities
   650  among similar interfaces.
   651  </p>
   652  
   653  <h3 id="t_and_equal_interface">
   654  Why doesn't type T satisfy the Equal interface?</h3>
   655  
   656  <p>
   657  Consider this simple interface to represent an object that can compare
   658  itself with another value:
   659  </p>
   660  
   661  <pre>
   662  type Equaler interface {
   663      Equal(Equaler) bool
   664  }
   665  </pre>
   666  
   667  <p>
   668  and this type, <code>T</code>:
   669  </p>
   670  
   671  <pre>
   672  type T int
   673  func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
   674  </pre>
   675  
   676  <p>
   677  Unlike the analogous situation in some polymorphic type systems,
   678  <code>T</code> does not implement <code>Equaler</code>.
   679  The argument type of <code>T.Equal</code> is <code>T</code>,
   680  not literally the required type <code>Equaler</code>.
   681  </p>
   682  
   683  <p>
   684  In Go, the type system does not promote the argument of
   685  <code>Equal</code>; that is the programmer's responsibility, as
   686  illustrated by the type <code>T2</code>, which does implement
   687  <code>Equaler</code>:
   688  </p>
   689  
   690  <pre>
   691  type T2 int
   692  func (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler
   693  </pre>
   694  
   695  <p>
   696  Even this isn't like other type systems, though, because in Go <em>any</em>
   697  type that satisfies <code>Equaler</code> could be passed as the
   698  argument to <code>T2.Equal</code>, and at run time we must
   699  check that the argument is of type <code>T2</code>.
   700  Some languages arrange to make that guarantee at compile time.
   701  </p>
   702  
   703  <p>
   704  A related example goes the other way:
   705  </p>
   706  
   707  <pre>
   708  type Opener interface {
   709     Open() Reader
   710  }
   711  
   712  func (t T3) Open() *os.File
   713  </pre>
   714  
   715  <p>
   716  In Go, <code>T3</code> does not satisfy <code>Opener</code>,
   717  although it might in another language.
   718  </p>
   719  
   720  <p>
   721  While it is true that Go's type system does less for the programmer
   722  in such cases, the lack of subtyping makes the rules about
   723  interface satisfaction very easy to state: are the function's names
   724  and signatures exactly those of the interface?
   725  Go's rule is also easy to implement efficiently.
   726  We feel these benefits offset the lack of
   727  automatic type promotion. Should Go one day adopt some form of generic
   728  typing, we expect there would be a way to express the idea of these
   729  examples and also have them be statically checked.
   730  </p>
   731  
   732  <h3 id="convert_slice_of_interface">
   733  Can I convert a []T to an []interface{}?</h3>
   734  
   735  <p>
   736  Not directly, because they do not have the same representation in memory.
   737  It is necessary to copy the elements individually to the destination
   738  slice. This example converts a slice of <code>int</code> to a slice of
   739  <code>interface{}</code>:
   740  </p>
   741  
   742  <pre>
   743  t := []int{1, 2, 3, 4}
   744  s := make([]interface{}, len(t))
   745  for i, v := range t {
   746      s[i] = v
   747  }
   748  </pre>
   749  
   750  <h3 id="nil_error">
   751  Why is my nil error value not equal to nil?
   752  </h3>
   753  
   754  <p>
   755  Under the covers, interfaces are implemented as two elements, a type and a value.
   756  The value, called the interface's dynamic value,
   757  is an arbitrary concrete value and the type is that of the value.
   758  For the <code>int</code> value 3, an interface value contains,
   759  schematically, (<code>int</code>, <code>3</code>).
   760  </p>
   761  
   762  <p>
   763  An interface value is <code>nil</code> only if the inner value and type are both unset,
   764  (<code>nil</code>, <code>nil</code>).
   765  In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
   766  If we store a pointer of type <code>*int</code> inside
   767  an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
   768  (<code>*int</code>, <code>nil</code>).
   769  Such an interface value will therefore be non-<code>nil</code>
   770  <em>even when the pointer inside is</em> <code>nil</code>.
   771  </p>
   772  
   773  <p>
   774  This situation can be confusing, and often arises when a <code>nil</code> value is
   775  stored inside an interface value such as an <code>error</code> return:
   776  </p>
   777  
   778  <pre>
   779  func returnsError() error {
   780  	var p *MyError = nil
   781  	if bad() {
   782  		p = ErrBad
   783  	}
   784  	return p // Will always return a non-nil error.
   785  }
   786  </pre>
   787  
   788  <p>
   789  If all goes well, the function returns a <code>nil</code> <code>p</code>,
   790  so the return value is an <code>error</code> interface
   791  value holding (<code>*MyError</code>, <code>nil</code>).
   792  This means that if the caller compares the returned error to <code>nil</code>,
   793  it will always look as if there was an error even if nothing bad happened.
   794  To return a proper <code>nil</code> <code>error</code> to the caller,
   795  the function must return an explicit <code>nil</code>:
   796  </p>
   797  
   798  
   799  <pre>
   800  func returnsError() error {
   801  	if bad() {
   802  		return ErrBad
   803  	}
   804  	return nil
   805  }
   806  </pre>
   807  
   808  <p>
   809  It's a good idea for functions
   810  that return errors always to use the <code>error</code> type in
   811  their signature (as we did above) rather than a concrete type such
   812  as <code>*MyError</code>, to help guarantee the error is
   813  created correctly. As an example,
   814  <a href="/pkg/os/#Open"><code>os.Open</code></a>
   815  returns an <code>error</code> even though, if not <code>nil</code>,
   816  it's always of concrete type
   817  <a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
   818  </p>
   819  
   820  <p>
   821  Similar situations to those described here can arise whenever interfaces are used.
   822  Just keep in mind that if any concrete value
   823  has been stored in the interface, the interface will not be <code>nil</code>.
   824  For more information, see
   825  <a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
   826  </p>
   827  
   828  
   829  <h3 id="unions">
   830  Why are there no untagged unions, as in C?</h3>
   831  
   832  <p>
   833  Untagged unions would violate Go's memory safety
   834  guarantees.
   835  </p>
   836  
   837  <h3 id="variant_types">
   838  Why does Go not have variant types?</h3>
   839  
   840  <p>
   841  Variant types, also known as algebraic types, provide a way to specify
   842  that a value might take one of a set of other types, but only those
   843  types. A common example in systems programming would specify that an
   844  error is, say, a network error, a security error or an application
   845  error and allow the caller to discriminate the source of the problem
   846  by examining the type of the error. Another example is a syntax tree
   847  in which each node can be a different type: declaration, statement,
   848  assignment and so on.
   849  </p>
   850  
   851  <p>
   852  We considered adding variant types to Go, but after discussion
   853  decided to leave them out because they overlap in confusing ways
   854  with interfaces. What would happen if the elements of a variant type
   855  were themselves interfaces?
   856  </p>
   857  
   858  <p>
   859  Also, some of what variant types address is already covered by the
   860  language. The error example is easy to express using an interface
   861  value to hold the error and a type switch to discriminate cases.  The
   862  syntax tree example is also doable, although not as elegantly.
   863  </p>
   864  
   865  <h2 id="values">Values</h2>
   866  
   867  <h3 id="conversions">
   868  Why does Go not provide implicit numeric conversions?</h3>
   869  <p>
   870  The convenience of automatic conversion between numeric types in C is
   871  outweighed by the confusion it causes.  When is an expression unsigned?
   872  How big is the value?  Does it overflow?  Is the result portable, independent
   873  of the machine on which it executes?
   874  It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
   875  are not easy to implement and inconsistent across architectures.
   876  For reasons of portability, we decided to make things clear and straightforward
   877  at the cost of some explicit conversions in the code.
   878  The definition of constants in Go&mdash;arbitrary precision values free
   879  of signedness and size annotations&mdash;ameliorates matters considerably,
   880  though.
   881  </p>
   882  
   883  <p>
   884  A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
   885  are distinct types even if <code>int</code> is a 64-bit type.  The <code>int</code>
   886  type is generic; if you care about how many bits an integer holds, Go
   887  encourages you to be explicit.
   888  </p>
   889  
   890  <h3 id="builtin_maps">
   891  Why are maps built in?</h3>
   892  <p>
   893  The same reason strings are: they are such a powerful and important data
   894  structure that providing one excellent implementation with syntactic support
   895  makes programming more pleasant.  We believe that Go's implementation of maps
   896  is strong enough that it will serve for the vast majority of uses.
   897  If a specific application can benefit from a custom implementation, it's possible
   898  to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
   899  </p>
   900  
   901  <h3 id="map_keys">
   902  Why don't maps allow slices as keys?</h3>
   903  <p>
   904  Map lookup requires an equality operator, which slices do not implement.
   905  They don't implement equality because equality is not well defined on such types;
   906  there are multiple considerations involving shallow vs. deep comparison, pointer vs.
   907  value comparison, how to deal with recursive types, and so on.
   908  We may revisit this issue&mdash;and implementing equality for slices
   909  will not invalidate any existing programs&mdash;but without a clear idea of what
   910  equality of slices should mean, it was simpler to leave it out for now.
   911  </p>
   912  
   913  <p>
   914  In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
   915  types can be used as map keys. Slices still do not have a definition of equality, though.
   916  </p>
   917  
   918  <h3 id="references">
   919  Why are maps, slices, and channels references while arrays are values?</h3>
   920  <p>
   921  There's a lot of history on that topic.  Early on, maps and channels
   922  were syntactically pointers and it was impossible to declare or use a
   923  non-pointer instance.  Also, we struggled with how arrays should work.
   924  Eventually we decided that the strict separation of pointers and
   925  values made the language harder to use.  Changing these
   926  types to act as references to the associated, shared data structures resolved
   927  these issues. This change added some regrettable complexity to the
   928  language but had a large effect on usability: Go became a more
   929  productive, comfortable language when it was introduced.
   930  </p>
   931  
   932  <h2 id="Writing_Code">Writing Code</h2>
   933  
   934  <h3 id="How_are_libraries_documented">
   935  How are libraries documented?</h3>
   936  
   937  <p>
   938  There is a program, <code>godoc</code>, written in Go, that extracts
   939  package documentation from the source code. It can be used on the
   940  command line or on the web. An instance is running at
   941  <a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
   942  In fact, <code>godoc</code> implements the full site at
   943  <a href="http://golang.org/">http://golang.org/</a>.
   944  </p>
   945  
   946  <h3 id="Is_there_a_Go_programming_style_guide">
   947  Is there a Go programming style guide?</h3>
   948  
   949  <p>
   950  Eventually, there may be a small number of rules to guide things
   951  like naming, layout, and file organization.
   952  The document <a href="effective_go.html">Effective Go</a>
   953  contains some style advice.
   954  More directly, the program <code>gofmt</code> is a pretty-printer
   955  whose purpose is to enforce layout rules; it replaces the usual
   956  compendium of do's and don'ts that allows interpretation.
   957  All the Go code in the repository has been run through <code>gofmt</code>.
   958  </p>
   959  
   960  <h3 id="How_do_I_submit_patches_to_the_Go_libraries">
   961  How do I submit patches to the Go libraries?</h3>
   962  
   963  <p>
   964  The library sources are in <code>go/src/pkg</code>.
   965  If you want to make a significant change, please discuss on the mailing list before embarking.
   966  </p>
   967  
   968  <p>
   969  See the document
   970  <a href="contribute.html">Contributing to the Go project</a>
   971  for more information about how to proceed.
   972  </p>
   973  
   974  <h3 id="Why_does_the_project_use_Mercurial_and_not_git">
   975  Why does the project use Mercurial and not git?</h3>
   976  
   977  <p>
   978  The Go project, hosted by Google Code at
   979  <a href="http://code.google.com/p/go">code.google.com/p/go</a>,
   980  uses Mercurial as its version control system.
   981  When the project launched,
   982  Google Code supported only Subversion and Mercurial.
   983  Mercurial was a better choice because of its plugin mechanism
   984  that allowed us to create the "codereview" plugin to connect
   985  the project to the excellent code review tools at
   986  <a href="http://codereview.appspot.com">codereview.appspot.com</a>.
   987  </p>
   988  
   989  <p>
   990  Programmers who work
   991  with the Go project's source rather than release downloads sometimes
   992  ask for the project to switch to git.
   993  That would be possible, but it would be a lot of work and
   994  would also require reimplementing the codereview plugin.
   995  Given that Mercurial works today, with code review support,
   996  combined with the Go project's mostly linear, non-branching use of
   997  version control, a switch to git doesn't seem worthwhile.
   998  </p>
   999  
  1000  <h3 id="git_https">
  1001  Why does "go get" use HTTPS when cloning a repository?</h3>
  1002  
  1003  <p>
  1004  Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
  1005  and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 
  1006  (git) and TCP port 22 (SSH).
  1007  When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
  1008  default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
  1009  The <code>go get</code> command therefore uses HTTPS for safety.
  1010  </p>
  1011  
  1012  <p>
  1013  If you use <code>git</code> and prefer to push changes through SSH using your existing key 
  1014  it's easy to work around this. For GitHub, try one of these solutions:
  1015  </p>
  1016  <ul>
  1017  <li>Manually clone the repository in the expected package directory:
  1018  <pre>
  1019  $ cd $GOPATH/src/github.com/username
  1020  $ git clone git@github.com:username/package.git
  1021  </pre>
  1022  </li>
  1023  <li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending
  1024  these two lines to <code>~/.gitconfig</code>:
  1025  <pre>
  1026  [url "git@github.com:"]
  1027  	pushInsteadOf = https://github.com/
  1028  </pre>
  1029  </li>
  1030  </ul>
  1031  
  1032  <h3 id="get_version">
  1033  How should I manage package versions using "go get"?</h3>
  1034  
  1035  <p>
  1036  "Go get" does not have any explicit concept of package versions.
  1037  Versioning is a source of significant complexity, especially in large code bases,
  1038  and we are unaware of any approach that works well at scale in a large enough
  1039  variety of situations to be appropriate to force on all Go users.
  1040  What "go get" and the larger Go toolchain do provide is isolation of
  1041  packages with different import paths.
  1042  For example, the standard library's <code>html/template</code> and <code>text/template</code>
  1043  coexist even though both are "package template".
  1044  This observation leads to some advice for package authors and package users.
  1045  </p>
  1046  
  1047  <p>
  1048  Packages intended for public use should try to maintain backwards compatibility as they evolve.
  1049  The <a href="/doc/go1compat.html">Go 1 compatibility guidelines</a> are a good reference here:
  1050  don't remove exported names, encourage tagged composite literals, and so on.
  1051  If different functionality is required, add a new name instead of changing an old one.
  1052  If a complete break is required, create a new package with a new import path.</p>
  1053  
  1054  <p>
  1055  If you're using an externally supplied package and worry that it might change in
  1056  unexpected ways, the simplest solution is to copy it to your local repository.
  1057  (This is the approach Google takes internally.)
  1058  Store the copy under a new import path that identifies it as a local copy.
  1059  For example, you might copy "original.com/pkg" to "you.com/external/original.com/pkg".
  1060  Keith Rarick's <a href="https://github.com/kr/goven">goven</a> is one tool to help automate this process.
  1061  </p>
  1062  
  1063  <h2 id="Pointers">Pointers and Allocation</h2>
  1064  
  1065  <h3 id="pass_by_value">
  1066  When are function parameters passed by value?</h3>
  1067  
  1068  <p>
  1069  As in all languages in the C family, everything in Go is passed by value.
  1070  That is, a function always gets a copy of the
  1071  thing being passed, as if there were an assignment statement assigning the
  1072  value to the parameter.  For instance, passing an <code>int</code> value
  1073  to a function makes a copy of the <code>int</code>, and passing a pointer
  1074  value makes a copy of the pointer, but not the data it points to.
  1075  (See the next section for a discussion of how this affects method receivers.)
  1076  </p>
  1077  
  1078  <p>
  1079  Map and slice values behave like pointers: they are descriptors that
  1080  contain pointers to the underlying map or slice data.  Copying a map or
  1081  slice value doesn't copy the data it points to.  Copying an interface value
  1082  makes a copy of the thing stored in the interface value.  If the interface
  1083  value holds a struct, copying the interface value makes a copy of the
  1084  struct.  If the interface value holds a pointer, copying the interface value
  1085  makes a copy of the pointer, but again not the data it points to.
  1086  </p>
  1087  
  1088  <h3 id="pointer_to_interface">
  1089  When should I use a pointer to an interface?</h3>
  1090  
  1091  <p>
  1092  Almost never. Pointers to interface values arise only in rare, tricky situations involving
  1093  disguising an interface value's type for delayed evaluation.
  1094  </p>
  1095  
  1096  <p>
  1097  It is however a common mistake to pass a pointer to an interface value
  1098  to a function expecting an interface. The compiler will complain about this
  1099  error but the situation can still be confusing, because sometimes a
  1100  <a href="#different_method_sets">pointer
  1101  is necessary to satisfy an interface</a>.
  1102  The insight is that although a pointer to a concrete type can satisfy
  1103  an interface, with one exception <em>a pointer to an interface can never satisfy a interface</em>.
  1104  </p>
  1105  
  1106  <p>
  1107  Consider the variable declaration,
  1108  </p>
  1109  
  1110  <pre>
  1111  var w io.Writer
  1112  </pre>
  1113  
  1114  <p>
  1115  The printing function <code>fmt.Fprintf</code> takes as its first argument
  1116  a value that satisfies <code>io.Writer</code>—something that implements
  1117  the canonical <code>Write</code> method. Thus we can write
  1118  </p>
  1119  
  1120  <pre>
  1121  fmt.Fprintf(w, "hello, world\n")
  1122  </pre>
  1123  
  1124  <p>
  1125  If however we pass the address of <code>w</code>, the program will not compile.
  1126  </p>
  1127  
  1128  <pre>
  1129  fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
  1130  </pre>
  1131  
  1132  <p>
  1133  The one exception is that any value, even a pointer to an interface, can be assigned to
  1134  a variable of empty interface type (<code>interface{}</code>).
  1135  Even so, it's almost certainly a mistake if the value is a pointer to an interface;
  1136  the result can be confusing.
  1137  </p>
  1138  
  1139  <h3 id="methods_on_values_or_pointers">
  1140  Should I define methods on values or pointers?</h3>
  1141  
  1142  <pre>
  1143  func (s *MyStruct) pointerMethod() { } // method on pointer
  1144  func (s MyStruct)  valueMethod()   { } // method on value
  1145  </pre>
  1146  
  1147  <p>
  1148  For programmers unaccustomed to pointers, the distinction between these
  1149  two examples can be confusing, but the situation is actually very simple.
  1150  When defining a method on a type, the receiver (<code>s</code> in the above
  1151  examples) behaves exactly as if it were an argument to the method.
  1152  Whether to define the receiver as a value or as a pointer is the same
  1153  question, then, as whether a function argument should be a value or
  1154  a pointer.
  1155  There are several considerations.
  1156  </p>
  1157  
  1158  <p>
  1159  First, and most important, does the method need to modify the
  1160  receiver?
  1161  If it does, the receiver <em>must</em> be a pointer.
  1162  (Slices and maps act as references, so their story is a little
  1163  more subtle, but for instance to change the length of a slice
  1164  in a method the receiver must still be a pointer.)
  1165  In the examples above, if <code>pointerMethod</code> modifies
  1166  the fields of <code>s</code>,
  1167  the caller will see those changes, but <code>valueMethod</code>
  1168  is called with a copy of the caller's argument (that's the definition
  1169  of passing a value), so changes it makes will be invisible to the caller.
  1170  </p>
  1171  
  1172  <p>
  1173  By the way, pointer receivers are identical to the situation in Java,
  1174  although in Java the pointers are hidden under the covers; it's Go's
  1175  value receivers that are unusual.
  1176  </p>
  1177  
  1178  <p>
  1179  Second is the consideration of efficiency. If the receiver is large,
  1180  a big <code>struct</code> for instance, it will be much cheaper to
  1181  use a pointer receiver.
  1182  </p>
  1183  
  1184  <p>
  1185  Next is consistency. If some of the methods of the type must have
  1186  pointer receivers, the rest should too, so the method set is
  1187  consistent regardless of how the type is used.
  1188  See the section on <a href="#different_method_sets">method sets</a>
  1189  for details.
  1190  </p>
  1191  
  1192  <p>
  1193  For types such as basic types, slices, and small <code>structs</code>,
  1194  a value receiver is very cheap so unless the semantics of the method
  1195  requires a pointer, a value receiver is efficient and clear.
  1196  </p>
  1197  
  1198  
  1199  <h3 id="new_and_make">
  1200  What's the difference between new and make?</h3>
  1201  
  1202  <p>
  1203  In short: <code>new</code> allocates memory, <code>make</code> initializes
  1204  the slice, map, and channel types.
  1205  </p>
  1206  
  1207  <p>
  1208  See the <a href="/doc/effective_go.html#allocation_new">relevant section
  1209  of Effective Go</a> for more details.
  1210  </p>
  1211  
  1212  <h3 id="q_int_sizes">
  1213  What is the size of an <code>int</code> on a 64 bit machine?</h3>
  1214  
  1215  <p>
  1216  The sizes of <code>int</code> and <code>uint</code> are implementation-specific
  1217  but the same as each other on a given platform.
  1218  For portability, code that relies on a particular
  1219  size of value should use an explicitly sized type, like <code>int64</code>.
  1220  Prior to Go 1.1, the 64-bit Go compilers (both gc and gccgo) used
  1221  a 32-bit representation for <code>int</code>. As of Go 1.1 they use
  1222  a 64-bit representation.
  1223  On the other hand, floating-point scalars and complex
  1224  numbers are always sized: <code>float32</code>, <code>complex64</code>,
  1225  etc., because programmers should be aware of precision when using
  1226  floating-point numbers.
  1227  The default size of a floating-point constant is <code>float64</code>.
  1228  </p>
  1229  
  1230  <h3 id="stack_or_heap">
  1231  How do I know whether a variable is allocated on the heap or the stack?</h3>
  1232  
  1233  <p>
  1234  From a correctness standpoint, you don't need to know.
  1235  Each variable in Go exists as long as there are references to it.
  1236  The storage location chosen by the implementation is irrelevant to the
  1237  semantics of the language.
  1238  </p>
  1239  
  1240  <p>
  1241  The storage location does have an effect on writing efficient programs.
  1242  When possible, the Go compilers will allocate variables that are
  1243  local to a function in that function's stack frame.  However, if the
  1244  compiler cannot prove that the variable is not referenced after the
  1245  function returns, then the compiler must allocate the variable on the
  1246  garbage-collected heap to avoid dangling pointer errors.
  1247  Also, if a local variable is very large, it might make more sense
  1248  to store it on the heap rather than the stack.
  1249  </p>
  1250  
  1251  <p>
  1252  In the current compilers, if a variable has its address taken, that variable
  1253  is a candidate for allocation on the heap. However, a basic <em>escape
  1254  analysis</em> recognizes some cases when such variables will not
  1255  live past the return from the function and can reside on the stack.
  1256  </p>
  1257  
  1258  <h3 id="Why_does_my_Go_process_use_so_much_virtual_memory">
  1259  Why does my Go process use so much virtual memory?</h3>
  1260  
  1261  <p>
  1262  The Go memory allocator reserves a large region of virtual memory as an arena
  1263  for allocations. This virtual memory is local to the specific Go process; the
  1264  reservation does not deprive other processes of memory.
  1265  </p>
  1266  
  1267  <p>
  1268  To find the amount of actual memory allocated to a Go process, use the Unix
  1269  <code>top</code> command and consult the <code>RES</code> (Linux) or
  1270  <code>RSIZE</code> (Mac OS X) columns.
  1271  <!-- TODO(adg): find out how this works on Windows -->
  1272  </p>
  1273  
  1274  <h2 id="Concurrency">Concurrency</h2>
  1275  
  1276  <h3 id="What_operations_are_atomic_What_about_mutexes">
  1277  What operations are atomic? What about mutexes?</h3>
  1278  
  1279  <p>
  1280  We haven't fully defined it all yet, but some details about atomicity are
  1281  available in the <a href="/ref/mem">Go Memory Model specification</a>.
  1282  </p>
  1283  
  1284  <p>
  1285  Regarding mutexes, the <a href="/pkg/sync">sync</a>
  1286  package implements them, but we hope Go programming style will
  1287  encourage people to try higher-level techniques. In particular, consider
  1288  structuring your program so that only one goroutine at a time is ever
  1289  responsible for a particular piece of data.
  1290  </p>
  1291  
  1292  <p>
  1293  Do not communicate by sharing memory. Instead, share memory by communicating.
  1294  </p>
  1295  
  1296  <p>
  1297  See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk and its <a href="http://blog.golang.org/2010/07/share-memory-by-communicating.html">associated article</a> for a detailed discussion of this concept.
  1298  </p>
  1299  
  1300  <h3 id="Why_no_multi_CPU">
  1301  Why doesn't my multi-goroutine program use multiple CPUs?</h3>
  1302  
  1303  <p>
  1304  You must set the <code>GOMAXPROCS</code> shell environment variable
  1305  or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a>
  1306  of the runtime package to allow the
  1307  run-time support to utilize more than one OS thread.
  1308  </p>
  1309  
  1310  <p>
  1311  Programs that perform parallel computation should benefit from an increase in
  1312  <code>GOMAXPROCS</code>.
  1313  However, be aware that
  1314  <a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">concurrency
  1315  is not parallelism</a>.
  1316  </p>
  1317  
  1318  <h3 id="Why_GOMAXPROCS">
  1319  Why does using <code>GOMAXPROCS</code> &gt; 1 sometimes make my program
  1320  slower?</h3>
  1321  
  1322  <p>
  1323  It depends on the nature of your program.
  1324  Problems that are intrinsically sequential cannot be sped up by adding
  1325  more goroutines.
  1326  Concurrency only becomes parallelism when the problem is
  1327  intrinsically parallel.
  1328  </p>
  1329  
  1330  <p>
  1331  In practical terms, programs that spend more time
  1332  communicating on channels than doing computation
  1333  will experience performance degradation when using
  1334  multiple OS threads.
  1335  This is because sending data between threads involves switching
  1336  contexts, which has significant cost.
  1337  For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
  1338  from the Go specification has no significant parallelism although it launches many
  1339  goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than
  1340  to speed it up.
  1341  </p>
  1342  
  1343  <p>
  1344  Go's goroutine scheduler is not as good as it needs to be. In future, it
  1345  should recognize such cases and optimize its use of OS threads. For now,
  1346  <code>GOMAXPROCS</code> should be set on a per-application basis.
  1347  </p>
  1348  
  1349  <p>
  1350  For more detail on this topic see the talk entitled,
  1351  <a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency
  1352  is not Parallelism</a>.
  1353  
  1354  <h2 id="Functions_methods">Functions and Methods</h2>
  1355  
  1356  <h3 id="different_method_sets">
  1357  Why do T and *T have different method sets?</h3>
  1358  
  1359  <p>
  1360  From the <a href="/ref/spec#Types">Go Spec</a>:
  1361  </p>
  1362  
  1363  <blockquote>
  1364  The method set of any other named type <code>T</code> consists of all methods
  1365  with receiver type <code>T</code>. The method set of the corresponding pointer
  1366  type <code>*T</code> is the set of all methods with receiver <code>*T</code> or
  1367  <code>T</code> (that is, it also contains the method set of <code>T</code>).
  1368  </blockquote>
  1369  
  1370  <p>
  1371  If an interface value contains a pointer <code>*T</code>,
  1372  a method call can obtain a value by dereferencing the pointer,
  1373  but if an interface value contains a value <code>T</code>,
  1374  there is no useful way for a method call to obtain a pointer.
  1375  </p>
  1376  
  1377  <p>
  1378  Even in cases where the compiler could take the address of a value
  1379  to pass to the method, if the method modifies the value the changes
  1380  will be lost in the caller.
  1381  As a common example, this code:
  1382  </p>
  1383  
  1384  <pre>
  1385  var buf bytes.Buffer
  1386  io.Copy(buf, os.Stdin)
  1387  </pre>
  1388  
  1389  <p>
  1390  would copy standard input into a <i>copy</i> of <code>buf</code>,
  1391  not into <code>buf</code> itself.
  1392  This is almost never the desired behavior.
  1393  </p>
  1394  
  1395  <h3 id="closures_and_goroutines">
  1396  What happens with closures running as goroutines?</h3>
  1397  
  1398  <p>
  1399  Some confusion may arise when using closures with concurrency.
  1400  Consider the following program:
  1401  </p>
  1402  
  1403  <pre>
  1404  func main() {
  1405      done := make(chan bool)
  1406  
  1407      values := []string{"a", "b", "c"}
  1408      for _, v := range values {
  1409          go func() {
  1410              fmt.Println(v)
  1411              done &lt;- true
  1412          }()
  1413      }
  1414  
  1415      // wait for all goroutines to complete before exiting
  1416      for _ = range values {
  1417          &lt;-done
  1418      }
  1419  }
  1420  </pre>
  1421  
  1422  <p>
  1423  One might mistakenly expect to see <code>a, b, c</code> as the output.
  1424  What you'll probably see instead is <code>c, c, c</code>.  This is because
  1425  each iteration of the loop uses the same instance of the variable <code>v</code>, so
  1426  each closure shares that single variable. When the closure runs, it prints the
  1427  value of <code>v</code> at the time <code>fmt.Println</code> is executed,
  1428  but <code>v</code> may have been modified since the goroutine was launched.
  1429  To help detect this and other problems before they happen, run
  1430  <a href="http://golang.org/cmd/go/#hdr-Run_go_tool_vet_on_packages"><code>go vet</code></a>.
  1431  </p>
  1432  
  1433  <p>
  1434  To bind the current value of <code>v</code> to each closure as it is launched, one
  1435  must modify the inner loop to create a new variable each iteration.
  1436  One way is to pass the variable as an argument to the closure:
  1437  </p>
  1438  
  1439  <pre>
  1440      for _, v := range values {
  1441          go func(<b>u</b> string) {
  1442              fmt.Println(<b>u</b>)
  1443              done &lt;- true
  1444          }(<b>v</b>)
  1445      }
  1446  </pre>
  1447  
  1448  <p>
  1449  In this example, the value of <code>v</code> is passed as an argument to the
  1450  anonymous function. That value is then accessible inside the function as
  1451  the variable <code>u</code>.
  1452  </p>
  1453  
  1454  <p>
  1455  Even easier is just to create a new variable, using a declaration style that may
  1456  seem odd but works fine in Go:
  1457  </p>
  1458  
  1459  <pre>
  1460      for _, v := range values {
  1461          <b>v := v</b> // create a new 'v'.
  1462          go func() {
  1463              fmt.Println(<b>v</b>)
  1464              done &lt;- true
  1465          }()
  1466      }
  1467  </pre>
  1468  
  1469  <h2 id="Control_flow">Control flow</h2>
  1470  
  1471  <h3 id="Does_Go_have_a_ternary_form">
  1472  Does Go have the <code>?:</code> operator?</h3>
  1473  
  1474  <p>
  1475  There is no ternary form in Go. You may use the following to achieve the same
  1476  result:
  1477  </p>
  1478  
  1479  <pre>
  1480  if expr {
  1481      n = trueVal
  1482  } else {
  1483      n = falseVal
  1484  }
  1485  </pre>
  1486  
  1487  <h2 id="Packages_Testing">Packages and Testing</h2>
  1488  
  1489  <h3 id="How_do_I_create_a_multifile_package">
  1490  How do I create a multifile package?</h3>
  1491  
  1492  <p>
  1493  Put all the source files for the package in a directory by themselves.
  1494  Source files can refer to items from different files at will; there is
  1495  no need for forward declarations or a header file.
  1496  </p>
  1497  
  1498  <p>
  1499  Other than being split into multiple files, the package will compile and test
  1500  just like a single-file package.
  1501  </p>
  1502  
  1503  <h3 id="How_do_I_write_a_unit_test">
  1504  How do I write a unit test?</h3>
  1505  
  1506  <p>
  1507  Create a new file ending in <code>_test.go</code> in the same directory
  1508  as your package sources. Inside that file, <code>import "testing"</code>
  1509  and write functions of the form
  1510  </p>
  1511  
  1512  <pre>
  1513  func TestFoo(t *testing.T) {
  1514      ...
  1515  }
  1516  </pre>
  1517  
  1518  <p>
  1519  Run <code>go test</code> in that directory.
  1520  That script finds the <code>Test</code> functions,
  1521  builds a test binary, and runs it.
  1522  </p>
  1523  
  1524  <p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
  1525  the <a href="/pkg/testing/"><code>testing</code></a> package
  1526  and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details.
  1527  </p>
  1528  
  1529  <h3 id="testing_framework">
  1530  Where is my favorite helper function for testing?</h3>
  1531  
  1532  <p>
  1533  Go's standard <a href="/pkg/testing/"><code>testing</code></a> package makes it easy to write unit tests, but it lacks
  1534  features provided in other language's testing frameworks such as assertion functions.
  1535  An <a href="#assertions">earlier section</a> of this document explained why Go
  1536  doesn't have assertions, and
  1537  the same arguments apply to the use of <code>assert</code> in tests.
  1538  Proper error handling means letting other tests run after one has failed, so
  1539  that the person debugging the failure gets a complete picture of what is
  1540  wrong. It is more useful for a test to report that
  1541  <code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
  1542  2, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
  1543  answer for 2 and therefore no more tests were run. The programmer who
  1544  triggers the test failure may not be familiar with the code that fails.
  1545  Time invested writing a good error message now pays off later when the
  1546  test breaks.
  1547  </p>
  1548  
  1549  <p>
  1550  A related point is that testing frameworks tend to develop into mini-languages
  1551  of their own, with conditionals and controls and printing mechanisms,
  1552  but Go already has all those capabilities; why recreate them?
  1553  We'd rather write tests in Go; it's one fewer language to learn and the
  1554  approach keeps the tests straightforward and easy to understand.
  1555  </p>
  1556  
  1557  <p>
  1558  If the amount of extra code required to write
  1559  good errors seems repetitive and overwhelming, the test might work better if
  1560  table-driven, iterating over a list of inputs and outputs defined
  1561  in a data structure (Go has excellent support for data structure literals).
  1562  The work to write a good test and good error messages will then be amortized over many
  1563  test cases. The standard Go library is full of illustrative examples, such as in
  1564  <a href="/src/pkg/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>.
  1565  </p>
  1566  
  1567  
  1568  <h2 id="Implementation">Implementation</h2>
  1569  
  1570  <h3 id="What_compiler_technology_is_used_to_build_the_compilers">
  1571  What compiler technology is used to build the compilers?</h3>
  1572  
  1573  <p>
  1574  <code>Gccgo</code> has a front end written in C++, with a recursive descent parser coupled to the
  1575  standard GCC back end. <code>Gc</code> is written in C using
  1576  <code>yacc</code>/<code>bison</code> for the parser.
  1577  Although it's a new program, it fits in the Plan 9 C compiler suite
  1578  (<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>)
  1579  and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries.
  1580  </p>
  1581  
  1582  <p>
  1583  We considered writing <code>gc</code>, the original Go compiler, in Go itself but
  1584  elected not to do so because of the difficulties of bootstrapping and
  1585  especially of open source distribution&mdash;you'd need a Go compiler to
  1586  set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to
  1587  consider writing a compiler in Go, which might well happen.
  1588  (Go would be a
  1589  fine language in which to implement a compiler; a native lexer and
  1590  parser are already available in the <a href="/pkg/go/"><code>go</code></a> package
  1591  and a type checker is in the works.)
  1592  </p>
  1593  
  1594  <p>
  1595  We also considered using LLVM for <code>gc</code> but we felt it was too large and
  1596  slow to meet our performance goals.
  1597  </p>
  1598  
  1599  <h3 id="How_is_the_run_time_support_implemented">
  1600  How is the run-time support implemented?</h3>
  1601  
  1602  <p>
  1603  Again due to bootstrapping issues, the run-time code is mostly in C (with a
  1604  tiny bit of assembler) although Go is capable of implementing most of
  1605  it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
  1606  <code>Gc</code> uses a custom library to keep the footprint under
  1607  control; it is
  1608  compiled with a version of the Plan 9 C compiler that supports
  1609  segmented stacks for goroutines.
  1610  The <code>gccgo</code> compiler implements segmented
  1611  stacks on Linux only, supported by recent modifications to the gold linker.
  1612  </p>
  1613  
  1614  <h3 id="Why_is_my_trivial_program_such_a_large_binary">
  1615  Why is my trivial program such a large binary?</h3>
  1616  
  1617  <p>
  1618  The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>)
  1619  do static linking.  All Go binaries therefore include the Go
  1620  run-time, along with the run-time type information necessary to support dynamic
  1621  type checks, reflection, and even panic-time stack traces.
  1622  </p>
  1623  
  1624  <p>
  1625  A simple C "hello, world" program compiled and linked statically using gcc
  1626  on Linux is around 750 kB,
  1627  including an implementation of <code>printf</code>.
  1628  An equivalent Go program using <code>fmt.Printf</code>
  1629  is around 1.2 MB, but
  1630  that includes more powerful run-time support.
  1631  </p>
  1632  
  1633  <h3 id="unused_variables_and_imports">
  1634  Can I stop these complaints about my unused variable/import?</h3>
  1635  
  1636  <p>
  1637  The presence of an unused variable may indicate a bug, while
  1638  unused imports just slow down compilation.
  1639  Accumulate enough unused imports in your code tree and
  1640  things can get very slow.
  1641  For these reasons, Go allows neither.
  1642  </p>
  1643  
  1644  <p>
  1645  When developing code, it's common to create these situations
  1646  temporarily and it can be annoying to have to edit them out before the
  1647  program will compile.
  1648  </p>
  1649  
  1650  <p>
  1651  Some have asked for a compiler option to turn those checks off
  1652  or at least reduce them to warnings.
  1653  Such an option has not been added, though,
  1654  because compiler options should not affect the semantics of the
  1655  language and because the Go compiler does not report warnings, only
  1656  errors that prevent compilation.
  1657  </p>
  1658  
  1659  <p>
  1660  There are two reasons for having no warnings.  First, if it's worth
  1661  complaining about, it's worth fixing in the code.  (And if it's not
  1662  worth fixing, it's not worth mentioning.) Second, having the compiler
  1663  generate warnings encourages the implementation to warn about weak
  1664  cases that can make compilation noisy, masking real errors that
  1665  <em>should</em> be fixed.
  1666  </p>
  1667  
  1668  <p>
  1669  It's easy to address the situation, though.  Use the blank identifier
  1670  to let unused things persist while you're developing.
  1671  </p>
  1672  
  1673  <pre>
  1674  import "unused"
  1675  
  1676  // This declaration marks the import as used by referencing an
  1677  // item from the package.
  1678  var _ = unused.Item  // TODO: Delete before committing!
  1679  
  1680  func main() {
  1681      debugData := debug.Profile()
  1682      _ = debugData // Used only during debugging.
  1683      ....
  1684  }
  1685  </pre>
  1686  
  1687  <h2 id="Performance">Performance</h2>
  1688  
  1689  <h3 id="Why_does_Go_perform_badly_on_benchmark_x">
  1690  Why does Go perform badly on benchmark X?</h3>
  1691  
  1692  <p>
  1693  One of Go's design goals is to approach the performance of C for comparable
  1694  programs, yet on some benchmarks it does quite poorly, including several
  1695  in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries
  1696  for which versions of comparable performance are not available in Go.
  1697  For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a>
  1698  depends on a multi-precision math package, and the C
  1699  versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is
  1700  written in optimized assembler).
  1701  Benchmarks that depend on regular expressions
  1702  (<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are
  1703  essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
  1704  mature, highly optimized regular expression libraries like PCRE.
  1705  </p>
  1706  
  1707  <p>
  1708  Benchmark games are won by extensive tuning and the Go versions of most
  1709  of the benchmarks need attention.  If you measure comparable C
  1710  and Go programs
  1711  (<a href="/test/bench/shootout/reverse-complement.go">reverse-complement.go</a> is one example), you'll see the two
  1712  languages are much closer in raw performance than this suite would
  1713  indicate.
  1714  </p>
  1715  
  1716  <p>
  1717  Still, there is room for improvement. The compilers are good but could be
  1718  better, many libraries need major performance work, and the garbage collector
  1719  isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
  1720  garbage can have a huge effect.)
  1721  </p>
  1722  
  1723  <p>
  1724  In any case, Go can often be very competitive.
  1725  There has been significant improvement in the performance of many programs
  1726  as the language and tools have developed.
  1727  See the blog post about
  1728  <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
  1729  Go programs</a> for an informative example.
  1730  
  1731  <h2 id="change_from_c">Changes from C</h2>
  1732  
  1733  <h3 id="different_syntax">
  1734  Why is the syntax so different from C?</h3>
  1735  <p>
  1736  Other than declaration syntax, the differences are not major and stem
  1737  from two desires.  First, the syntax should feel light, without too
  1738  many mandatory keywords, repetition, or arcana.  Second, the language
  1739  has been designed to be easy to analyze
  1740  and can be parsed without a symbol table.  This makes it much easier
  1741  to build tools such as debuggers, dependency analyzers, automated
  1742  documentation extractors, IDE plug-ins, and so on.  C and its
  1743  descendants are notoriously difficult in this regard.
  1744  </p>
  1745  
  1746  <h3 id="declarations_backwards">
  1747  Why are declarations backwards?</h3>
  1748  <p>
  1749  They're only backwards if you're used to C. In C, the notion is that a
  1750  variable is declared like an expression denoting its type, which is a
  1751  nice idea, but the type and expression grammars don't mix very well and
  1752  the results can be confusing; consider function pointers.  Go mostly
  1753  separates expression and type syntax and that simplifies things (using
  1754  prefix <code>*</code> for pointers is an exception that proves the rule).  In C,
  1755  the declaration
  1756  </p>
  1757  <pre>
  1758      int* a, b;
  1759  </pre>
  1760  <p>
  1761  declares <code>a</code> to be a pointer but not <code>b</code>; in Go
  1762  </p>
  1763  <pre>
  1764      var a, b *int
  1765  </pre>
  1766  <p>
  1767  declares both to be pointers.  This is clearer and more regular.
  1768  Also, the <code>:=</code> short declaration form argues that a full variable
  1769  declaration should present the same order as <code>:=</code> so
  1770  </p>
  1771  <pre>
  1772      var a uint64 = 1
  1773  </pre>
  1774  <p>
  1775  has the same effect as
  1776  </p>
  1777  <pre>
  1778      a := uint64(1)
  1779  </pre>
  1780  <p>
  1781  Parsing is also simplified by having a distinct grammar for types that
  1782  is not just the expression grammar; keywords such as <code>func</code>
  1783  and <code>chan</code> keep things clear.
  1784  </p>
  1785  
  1786  <p>
  1787  See the article about
  1788  <a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
  1789  for more details.
  1790  </p>
  1791  
  1792  <h3 id="no_pointer_arithmetic">
  1793  Why is there no pointer arithmetic?</h3>
  1794  <p>
  1795  Safety.  Without pointer arithmetic it's possible to create a
  1796  language that can never derive an illegal address that succeeds
  1797  incorrectly.  Compiler and hardware technology have advanced to the
  1798  point where a loop using array indices can be as efficient as a loop
  1799  using pointer arithmetic.  Also, the lack of pointer arithmetic can
  1800  simplify the implementation of the garbage collector.
  1801  </p>
  1802  
  1803  <h3 id="inc_dec">
  1804  Why are <code>++</code> and <code>--</code> statements and not expressions?  And why postfix, not prefix?</h3>
  1805  <p>
  1806  Without pointer arithmetic, the convenience value of pre- and postfix
  1807  increment operators drops.  By removing them from the expression
  1808  hierarchy altogether, expression syntax is simplified and the messy
  1809  issues around order of evaluation of <code>++</code> and <code>--</code>
  1810  (consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
  1811  are eliminated as well.  The simplification is
  1812  significant.  As for postfix vs. prefix, either would work fine but
  1813  the postfix version is more traditional; insistence on prefix arose
  1814  with the STL, a library for a language whose name contains, ironically, a
  1815  postfix increment.
  1816  </p>
  1817  
  1818  <h3 id="semicolons">
  1819  Why are there braces but no semicolons? And why can't I put the opening
  1820  brace on the next line?</h3>
  1821  <p>
  1822  Go uses brace brackets for statement grouping, a syntax familiar to
  1823  programmers who have worked with any language in the C family.
  1824  Semicolons, however, are for parsers, not for people, and we wanted to
  1825  eliminate them as much as possible.  To achieve this goal, Go borrows
  1826  a trick from BCPL: the semicolons that separate statements are in the
  1827  formal grammar but are injected automatically, without lookahead, by
  1828  the lexer at the end of any line that could be the end of a statement.
  1829  This works very well in practice but has the effect that it forces a
  1830  brace style.  For instance, the opening brace of a function cannot
  1831  appear on a line by itself.
  1832  </p>
  1833  
  1834  <p>
  1835  Some have argued that the lexer should do lookahead to permit the
  1836  brace to live on the next line.  We disagree.  Since Go code is meant
  1837  to be formatted automatically by
  1838  <a href="/cmd/gofmt/"><code>gofmt</code></a>,
  1839  <i>some</i> style must be chosen.  That style may differ from what
  1840  you've used in C or Java, but Go is a new language and
  1841  <code>gofmt</code>'s style is as good as any other.  More
  1842  important&mdash;much more important&mdash;the advantages of a single,
  1843  programmatically mandated format for all Go programs greatly outweigh
  1844  any perceived disadvantages of the particular style.
  1845  Note too that Go's style means that an interactive implementation of
  1846  Go can use the standard syntax one line at a time without special rules.
  1847  </p>
  1848  
  1849  <h3 id="garbage_collection">
  1850  Why do garbage collection?  Won't it be too expensive?</h3>
  1851  <p>
  1852  One of the biggest sources of bookkeeping in systems programs is
  1853  memory management.  We feel it's critical to eliminate that
  1854  programmer overhead, and advances in garbage collection
  1855  technology in the last few years give us confidence that we can
  1856  implement it with low enough overhead and no significant
  1857  latency.
  1858  </p>
  1859  
  1860  <p>
  1861  Another point is that a large part of the difficulty of concurrent
  1862  and multi-threaded programming is memory management;
  1863  as objects get passed among threads it becomes cumbersome
  1864  to guarantee they become freed safely.
  1865  Automatic garbage collection makes concurrent code far easier to write.
  1866  Of course, implementing garbage collection in a concurrent environment is
  1867  itself a challenge, but meeting it once rather than in every
  1868  program helps everyone.
  1869  </p>
  1870  
  1871  <p>
  1872  Finally, concurrency aside, garbage collection makes interfaces
  1873  simpler because they don't need to specify how memory is managed across them.
  1874  </p>
  1875  
  1876  <p>
  1877  The current implementation is a parallel mark-and-sweep
  1878  collector but a future version might take a different approach.
  1879  </p>
  1880  
  1881  <p>
  1882  On the topic of performance, keep in mind that Go gives the programmer
  1883  considerable control over memory layout and allocation, much more than
  1884  is typical in garbage-collected languages. A careful programmer can reduce
  1885  the garbage collection overhead dramatically by using the language well;
  1886  see the article about
  1887  <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
  1888  Go programs</a> for a worked example, including a demonstration of Go's
  1889  profiling tools.
  1890  </p>