"Fossies" - the Fresh Open Source Software Archive

Member "go/doc/go_faq.html" (9 Sep 2020, 90087 Bytes) of package /windows/misc/go1.14.9.windows-386.zip:

As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) HTML source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

    1 <!--{
    2     "Title": "Frequently Asked Questions (FAQ)",
    3     "Path": "/doc/faq"
    4 }-->
    6 <h2 id="Origins">Origins</h2>
    8 <h3 id="What_is_the_purpose_of_the_project">
    9 What is the purpose of the project?</h3>
   11 <p>
   12 At the time of Go's inception, only a decade ago, the programming world was different from today.
   13 Production software was usually written in C++ or Java,
   14 GitHub did not exist, most computers were not yet multiprocessors,
   15 and other than Visual Studio and Eclipse there were few IDEs or other high-level tools available
   16 at all, let alone for free on the Internet.
   17 </p>
   19 <p>
   20 Meanwhile, we had become frustrated by the undue complexity required to use
   21 the languages we worked with to develop server software.
   22 Computers had become enormously quicker since languages such as
   23 C, C++ and Java were first developed but the act of programming had not
   24 itself advanced nearly as much.
   25 Also, it was clear that multiprocessors were becoming universal but
   26 most languages offered little help to program them efficiently
   27 and safely.
   28 </p>
   30 <p>
   31 We decided to take a step back and think about what major issues were
   32 going to dominate software engineering in the years ahead as technology
   33 developed, and how a new language might help address them.
   34 For instance, the rise of multicore CPUs argued that a language should
   35 provide first-class support for some sort of concurrency or parallelism.
   36 And to make resource management tractable in a large concurrent program,
   37 garbage collection, or at least some sort of safe automatic memory management was required.
   38 </p>
   40 <p>
   41 These considerations led to
   42 <a href="https://commandcenter.blogspot.com/2017/09/go-ten-years-and-climbing.html">a
   43 series of discussions</a> from which Go arose, first as a set of ideas and
   44 desiderata, then as a language.
   45 An overarching goal was that Go do more to help the working programmer
   46 by enabling tooling, automating mundane tasks such as code formatting,
   47 and removing obstacles to working on large code bases.
   48 </p>
   50 <p>
   51 A much more expansive description of the goals of Go and how
   52 they are met, or at least approached, is available in the article,
   53 <a href="//talks.golang.org/2012/splash.article">Go at Google:
   54 Language Design in the Service of Software Engineering</a>.
   55 </p>
   57 <h3 id="history">
   58 What is the history of the project?</h3>
   59 <p>
   60 Robert Griesemer, Rob Pike and Ken Thompson started sketching the
   61 goals for a new language on the white board on September 21, 2007.
   62 Within a few days the goals had settled into a plan to do something
   63 and a fair idea of what it would be.  Design continued part-time in
   64 parallel with unrelated work.  By January 2008, Ken had started work
   65 on a compiler with which to explore ideas; it generated C code as its
   66 output.  By mid-year the language had become a full-time project and
   67 had settled enough to attempt a production compiler.  In May 2008,
   68 Ian Taylor independently started on a GCC front end for Go using the
   69 draft specification.  Russ Cox joined in late 2008 and helped move the language
   70 and libraries from prototype to reality.
   71 </p>
   73 <p>
   74 Go became a public open source project on November 10, 2009.
   75 Countless people from the community have contributed ideas, discussions, and code.
   76 </p>
   78 <p>
   79 There are now millions of Go programmers—gophers—around the world,
   80 and there are more every day.
   81 Go's success has far exceeded our expectations.
   82 </p>
   84 <h3 id="gopher">
   85 What's the origin of the gopher mascot?</h3>
   87 <p>
   88 The mascot and logo were designed by
   89 <a href="https://reneefrench.blogspot.com">Renée French</a>, who also designed
   90 <a href="https://9p.io/plan9/glenda.html">Glenda</a>,
   91 the Plan 9 bunny.
   92 A <a href="https://blog.golang.org/gopher">blog post</a>
   93 about the gopher explains how it was
   94 derived from one she used for a <a href="https://wfmu.org/">WFMU</a>
   95 T-shirt design some years ago.
   96 The logo and mascot are covered by the
   97 <a href="https://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
   98 license.
   99 </p>
  101 <p>
  102 The gopher has a
  103 <a href="/doc/gopher/modelsheet.jpg">model sheet</a>
  104 illustrating his characteristics and how to represent them correctly.
  105 The model sheet was first shown in a
  106 <a href="https://www.youtube.com/watch?v=4rw_B4yY69k">talk</a>
  107 by Renée at Gophercon in 2016.
  108 He has unique features; he's the <em>Go gopher</em>, not just any old gopher.
  109 </p>
  111 <h3 id="go_or_golang">
  112 Is the language called Go or Golang?</h3>
  114 <p>
  115 The language is called Go.
  116 The "golang" moniker arose because the web site is
  117 <a href="https://golang.org">golang.org</a>, not
  118 go.org, which was not available to us.
  119 Many use the golang name, though, and it is handy as
  120 a label.
  121 For instance, the Twitter tag for the language is "#golang".
  122 The language's name is just plain Go, regardless.
  123 </p>
  125 <p>
  126 A side note: Although the
  127 <a href="https://blog.golang.org/go-brand">official logo</a>
  128 has two capital letters, the language name is written Go, not GO.
  129 </p>
  131 <h3 id="creating_a_new_language">
  132 Why did you create a new language?</h3>
  134 <p>
  135 Go was born out of frustration with existing languages and
  136 environments for the work we were doing at Google.
  137 Programming had become too
  138 difficult and the choice of languages was partly to blame.  One had to
  139 choose either efficient compilation, efficient execution, or ease of
  140 programming; all three were not available in the same mainstream
  141 language.  Programmers who could were choosing ease over
  142 safety and efficiency by moving to dynamically typed languages such as
  143 Python and JavaScript rather than C++ or, to a lesser extent, Java.
  144 </p>
  146 <p>
  147 We were not alone in our concerns.
  148 After many years with a pretty quiet landscape for programming languages,
  149 Go was among the first of several new languages—Rust,
  150 Elixir, Swift, and more—that have made programming language development
  151 an active, almost mainstream field again.
  152 </p>
  154 <p>
  155 Go addressed these issues by attempting to combine the ease of programming of an interpreted,
  156 dynamically typed
  157 language with the efficiency and safety of a statically typed, compiled language.
  158 It also aimed to be modern, with support for networked and multicore
  159 computing.  Finally, working with Go is intended to be <i>fast</i>: it should take
  160 at most a few seconds to build a large executable on a single computer.
  161 To meet these goals required addressing a number of
  162 linguistic issues: an expressive but lightweight type system;
  163 concurrency and garbage collection; rigid dependency specification;
  164 and so on.  These cannot be addressed well by libraries or tools; a new
  165 language was called for.
  166 </p>
  168 <p>
  169 The article <a href="//talks.golang.org/2012/splash.article">Go at Google</a>
  170 discusses the background and motivation behind the design of the Go language,
  171 as well as providing more detail about many of the answers presented in this FAQ.
  172 </p>
  175 <h3 id="ancestors">
  176 What are Go's ancestors?</h3>
  177 <p>
  178 Go is mostly in the C family (basic syntax),
  179 with significant input from the Pascal/Modula/Oberon
  180 family (declarations, packages),
  181 plus some ideas from languages
  182 inspired by Tony Hoare's CSP,
  183 such as Newsqueak and Limbo (concurrency).
  184 However, it is a new language across the board.
  185 In every respect the language was designed by thinking
  186 about what programmers do and how to make programming, at least the
  187 kind of programming we do, more effective, which means more fun.
  188 </p>
  190 <h3 id="principles">
  191 What are the guiding principles in the design?</h3>
  193 <p>
  194 When Go was designed, Java and C++ were the most commonly
  195 used languages for writing servers, at least at Google.
  196 We felt that these languages required
  197 too much bookkeeping and repetition.
  198 Some programmers reacted by moving towards more dynamic,
  199 fluid languages like Python, at the cost of efficiency and
  200 type safety.
  201 We felt it should be possible to have the efficiency,
  202 the safety, and the fluidity in a single language.
  203 </p>
  205 <p>
  206 Go attempts to reduce the amount of typing in both senses of the word.
  207 Throughout its design, we have tried to reduce clutter and
  208 complexity.  There are no forward declarations and no header files;
  209 everything is declared exactly once.  Initialization is expressive,
  210 automatic, and easy to use.  Syntax is clean and light on keywords.
  211 Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
  212 simple type derivation using the <code>:=</code>
  213 declare-and-initialize construct.  And perhaps most radically, there
  214 is no type hierarchy: types just <i>are</i>, they don't have to
  215 announce their relationships.  These simplifications allow Go to be
  216 expressive yet comprehensible without sacrificing, well, sophistication.
  217 </p>
  218 <p>
  219 Another important principle is to keep the concepts orthogonal.
  220 Methods can be implemented for any type; structures represent data while
  221 interfaces represent abstraction; and so on.  Orthogonality makes it
  222 easier to understand what happens when things combine.
  223 </p>
  225 <h2 id="Usage">Usage</h2>
  227 <h3 id="internal_usage">
  228 Is Google using Go internally?</h3>
  230 <p>
  231 Yes. Go is used widely in production inside Google.
  232 One easy example is the server behind
  233 <a href="//golang.org">golang.org</a>.
  234 It's just the <a href="/cmd/godoc"><code>godoc</code></a>
  235 document server running in a production configuration on
  236 <a href="https://developers.google.com/appengine/">Google App Engine</a>.
  237 </p>
  239 <p>
  240 A more significant instance is Google's download server, <code>dl.google.com</code>,
  241 which delivers Chrome binaries and other large installables such as <code>apt-get</code>
  242 packages.
  243 </p>
  245 <p>
  246 Go is not the only language used at Google, far from it, but it is a key language
  247 for a number of areas including
  248 <a href="https://talks.golang.org/2013/go-sreops.slide">site reliability
  249 engineering (SRE)</a>
  250 and large-scale data processing.
  251 </p>
  253 <h3 id="external_usage">
  254 What other companies use Go?</h3>
  256 <p>
  257 Go usage is growing worldwide, especially but by no means exclusively
  258 in the cloud computing space.
  259 A couple of major cloud infrastructure projects written in Go are
  260 Docker and Kubernetes,
  261 but there are many more.
  262 </p>
  264 <p>
  265 It's not just cloud, though.
  266 The Go Wiki includes a
  267 <a href="https://github.com/golang/go/wiki/GoUsers">page</a>,
  268 updated regularly, that lists some of the many companies using Go.
  269 </p>
  271 <p>
  272 The Wiki also has a page with links to
  273 <a href="https://github.com/golang/go/wiki/SuccessStories">success stories</a>
  274 about companies and projects that are using the language.
  275 </p>
  277 <h3 id="Do_Go_programs_link_with_Cpp_programs">
  278 Do Go programs link with C/C++ programs?</h3>
  280 <p>
  281 It is possible to use C and Go together in the same address space,
  282 but it is not a natural fit and can require special interface software.
  283 Also, linking C with Go code gives up the memory
  284 safety and stack management properties that Go provides.
  285 Sometimes it's absolutely necessary to use C libraries to solve a problem,
  286 but doing so always introduces an element of risk not present with
  287 pure Go code, so do so with care.
  288 </p>
  290 <p>
  291 If you do need to use C with Go, how to proceed depends on the Go
  292 compiler implementation.
  293 There are three Go compiler implementations supported by the
  294 Go team.
  295 These are <code>gc</code>, the default compiler,
  296 <code>gccgo</code>, which uses the GCC back end,
  297 and a somewhat less mature <code>gollvm</code>, which uses the LLVM infrastructure.
  298 </p>
  300 <p>
  301 <code>Gc</code> uses a different calling convention and linker from C and
  302 therefore cannot be called directly from C programs, or vice versa.
  303 The <a href="/cmd/cgo/"><code>cgo</code></a> program provides the mechanism for a
  304 &ldquo;foreign function interface&rdquo; to allow safe calling of
  305 C libraries from Go code.
  306 SWIG extends this capability to C++ libraries.
  307 </p>
  309 <p>
  310 You can also use <code>cgo</code> and SWIG with <code>Gccgo</code> and <code>gollvm</code>.
  311 Since they use a traditional API, it's also possible, with great care,
  312 to link code from these compilers directly with GCC/LLVM-compiled C or C++ programs.
  313 However, doing so safely requires an understanding of the calling conventions for
  314 all languages concerned, as well as concern for stack limits when calling C or C++
  315 from Go.
  316 </p>
  318 <h3 id="ide">
  319 What IDEs does Go support?</h3>
  321 <p>
  322 The Go project does not include a custom IDE, but the language and
  323 libraries have been designed to make it easy to analyze source code.
  324 As a consequence, most well-known editors and IDEs support Go well,
  325 either directly or through a plugin.
  326 </p>
  328 <p>
  329 The list of well-known IDEs and editors that have good Go support
  330 available includes Emacs, Vim, VSCode, Atom, Eclipse, Sublime, IntelliJ
  331 (through a custom variant called Goland), and many more.
  332 Chances are your favorite environment is a productive one for
  333 programming in Go.
  334 </p>
  336 <h3 id="protocol_buffers">
  337 Does Go support Google's protocol buffers?</h3>
  339 <p>
  340 A separate open source project provides the necessary compiler plugin and library.
  341 It is available at
  342 <a href="//github.com/golang/protobuf">github.com/golang/protobuf/</a>.
  343 </p>
  346 <h3 id="Can_I_translate_the_Go_home_page">
  347 Can I translate the Go home page into another language?</h3>
  349 <p>
  350 Absolutely. We encourage developers to make Go Language sites in their own languages.
  351 However, if you choose to add the Google logo or branding to your site
  352 (it does not appear on <a href="//golang.org/">golang.org</a>),
  353 you will need to abide by the guidelines at
  354 <a href="//www.google.com/permissions/guidelines.html">www.google.com/permissions/guidelines.html</a>
  355 </p>
  357 <h2 id="Design">Design</h2>
  359 <h3 id="runtime">
  360 Does Go have a runtime?</h3>
  362 <p>
  363 Go does have an extensive library, called the <em>runtime</em>,
  364 that is part of every Go program.
  365 The runtime library implements garbage collection, concurrency,
  366 stack management, and other critical features of the Go language.
  367 Although it is more central to the language, Go's runtime is analogous
  368 to <code>libc</code>, the C library.
  369 </p>
  371 <p>
  372 It is important to understand, however, that Go's runtime does not
  373 include a virtual machine, such as is provided by the Java runtime.
  374 Go programs are compiled ahead of time to native machine code
  375 (or JavaScript or WebAssembly, for some variant implementations).
  376 Thus, although the term is often used to describe the virtual
  377 environment in which a program runs, in Go the word &ldquo;runtime&rdquo;
  378 is just the name given to the library providing critical language services.
  379 </p>
  381 <h3 id="unicode_identifiers">
  382 What's up with Unicode identifiers?</h3>
  384 <p>
  385 When designing Go, we wanted to make sure that it was not
  386 overly ASCII-centric,
  387 which meant extending the space of identifiers from the
  388 confines of 7-bit ASCII.
  389 Go's rule&mdash;identifier characters must be
  390 letters or digits as defined by Unicode&mdash;is simple to understand
  391 and to implement but has restrictions.
  392 Combining characters are
  393 excluded by design, for instance,
  394 and that excludes some languages such as Devanagari.
  395 </p>
  397 <p>
  398 This rule has one other unfortunate consequence.
  399 Since an exported identifier must begin with an
  400 upper-case letter, identifiers created from characters
  401 in some languages can, by definition, not be exported.
  402 For now the
  403 only solution is to use something like <code>X日本語</code>, which
  404 is clearly unsatisfactory.
  405 </p>
  407 <p>
  408 Since the earliest version of the language, there has been considerable
  409 thought into how best to expand the identifier space to accommodate
  410 programmers using other native languages.
  411 Exactly what to do remains an active topic of discussion, and a future
  412 version of the language may be more liberal in its definition
  413 of an identifier.
  414 For instance, it might adopt some of the ideas from the Unicode
  415 organization's <a href="http://unicode.org/reports/tr31/">recommendations</a>
  416 for identifiers.
  417 Whatever happens, it must be done compatibly while preserving
  418 (or perhaps expanding) the way letter case determines visibility of
  419 identifiers, which remains one of our favorite features of Go.
  420 </p>
  422 <p>
  423 For the time being, we have a simple rule that can be expanded later
  424 without breaking programs, one that avoids bugs that would surely arise
  425 from a rule that admits ambiguous identifiers.
  426 </p>
  428 <h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
  430 <p>
  431 Every language contains novel features and omits someone's favorite
  432 feature. Go was designed with an eye on felicity of programming, speed of
  433 compilation, orthogonality of concepts, and the need to support features
  434 such as concurrency and garbage collection. Your favorite feature may be
  435 missing because it doesn't fit, because it affects compilation speed or
  436 clarity of design, or because it would make the fundamental system model
  437 too difficult.
  438 </p>
  440 <p>
  441 If it bothers you that Go is missing feature <var>X</var>,
  442 please forgive us and investigate the features that Go does have. You might find that
  443 they compensate in interesting ways for the lack of <var>X</var>.
  444 </p>
  446 <h3 id="generics">
  447 Why does Go not have generic types?</h3>
  448 <p>
  449 Generics may well be added at some point.  We don't feel an urgency for
  450 them, although we understand some programmers do.
  451 </p>
  453 <p>
  454 Go was intended as a language for writing server programs that would be
  455 easy to maintain over time.
  456 (See <a href="https://talks.golang.org/2012/splash.article">this
  457 article</a> for more background.)
  458 The design concentrated on things like scalability, readability, and
  459 concurrency.
  460 Polymorphic programming did not seem essential to the language's
  461 goals at the time, and so was left out for simplicity.
  462 </p>
  464 <p>
  465 The language is more mature now, and there is scope to consider
  466 some form of generic programming.
  467 However, there remain some caveats.
  468 </p>
  470 <p>
  471 Generics are convenient but they come at a cost in
  472 complexity in the type system and run-time.  We haven't yet found a
  473 design that gives value proportionate to the complexity, although we
  474 continue to think about it.  Meanwhile, Go's built-in maps and slices,
  475 plus the ability to use the empty interface to construct containers
  476 (with explicit unboxing) mean in many cases it is possible to write
  477 code that does what generics would enable, if less smoothly.
  478 </p>
  480 <p>
  481 The topic remains open.
  482 For a look at several previous unsuccessful attempts to
  483 design a good generics solution for Go, see
  484 <a href="https://golang.org/issue/15292">this proposal</a>.
  485 </p>
  487 <h3 id="exceptions">
  488 Why does Go not have exceptions?</h3>
  489 <p>
  490 We believe that coupling exceptions to a control
  491 structure, as in the <code>try-catch-finally</code> idiom, results in
  492 convoluted code.  It also tends to encourage programmers to label
  493 too many ordinary errors, such as failing to open a file, as
  494 exceptional.
  495 </p>
  497 <p>
  498 Go takes a different approach.  For plain error handling, Go's multi-value
  499 returns make it easy to report an error without overloading the return value.
  500 <a href="/doc/articles/error_handling.html">A canonical error type, coupled
  501 with Go's other features</a>, makes error handling pleasant but quite different
  502 from that in other languages.
  503 </p>
  505 <p>
  506 Go also has a couple
  507 of built-in functions to signal and recover from truly exceptional
  508 conditions.  The recovery mechanism is executed only as part of a
  509 function's state being torn down after an error, which is sufficient
  510 to handle catastrophe but requires no extra control structures and,
  511 when used well, can result in clean error-handling code.
  512 </p>
  514 <p>
  515 See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details.
  516 Also, the <a href="https://blog.golang.org/errors-are-values">Errors are values</a> blog post
  517 describes one approach to handling errors cleanly in Go by demonstrating that,
  518 since errors are just values, the full power of Go can deployed in error handling.
  519 </p>
  521 <h3 id="assertions">
  522 Why does Go not have assertions?</h3>
  524 <p>
  525 Go doesn't provide assertions. They are undeniably convenient, but our
  526 experience has been that programmers use them as a crutch to avoid thinking
  527 about proper error handling and reporting. Proper error handling means that
  528 servers continue to operate instead of crashing after a non-fatal error.
  529 Proper error reporting means that errors are direct and to the point,
  530 saving the programmer from interpreting a large crash trace. Precise
  531 errors are particularly important when the programmer seeing the errors is
  532 not familiar with the code.
  533 </p>
  535 <p>
  536 We understand that this is a point of contention. There are many things in
  537 the Go language and libraries that differ from modern practices, simply
  538 because we feel it's sometimes worth trying a different approach.
  539 </p>
  541 <h3 id="csp">
  542 Why build concurrency on the ideas of CSP?</h3>
  543 <p>
  544 Concurrency and multi-threaded programming have over time
  545 developed a reputation for difficulty.  We believe this is due partly to complex
  546 designs such as
  547 <a href="https://en.wikipedia.org/wiki/POSIX_Threads">pthreads</a>
  548 and partly to overemphasis on low-level details
  549 such as mutexes, condition variables, and memory barriers.
  550 Higher-level interfaces enable much simpler code, even if there are still
  551 mutexes and such under the covers.
  552 </p>
  554 <p>
  555 One of the most successful models for providing high-level linguistic support
  556 for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
  557 Occam and Erlang are two well known languages that stem from CSP.
  558 Go's concurrency primitives derive from a different part of the family tree
  559 whose main contribution is the powerful notion of channels as first class objects.
  560 Experience with several earlier languages has shown that the CSP model
  561 fits well into a procedural language framework.
  562 </p>
  564 <h3 id="goroutines">
  565 Why goroutines instead of threads?</h3>
  566 <p>
  567 Goroutines are part of making concurrency easy to use.  The idea, which has
  568 been around for a while, is to multiplex independently executing
  569 functions&mdash;coroutines&mdash;onto a set of threads.
  570 When a coroutine blocks, such as by calling a blocking system call,
  571 the run-time automatically moves other coroutines on the same operating
  572 system thread to a different, runnable thread so they won't be blocked.
  573 The programmer sees none of this, which is the point.
  574 The result, which we call goroutines, can be very cheap: they have little
  575 overhead beyond the memory for the stack, which is just a few kilobytes.
  576 </p>
  578 <p>
  579 To make the stacks small, Go's run-time uses resizable, bounded stacks.  A newly
  580 minted goroutine is given a few kilobytes, which is almost always enough.
  581 When it isn't, the run-time grows (and shrinks) the memory for storing
  582 the stack automatically, allowing many goroutines to live in a modest
  583 amount of memory.
  584 The CPU overhead averages about three cheap instructions per function call.
  585 It is practical to create hundreds of thousands of goroutines in the same
  586 address space.
  587 If goroutines were just threads, system resources would
  588 run out at a much smaller number.
  589 </p>
  591 <h3 id="atomic_maps">
  592 Why are map operations not defined to be atomic?</h3>
  594 <p>
  595 After long discussion it was decided that the typical use of maps did not require
  596 safe access from multiple goroutines, and in those cases where it did, the map was
  597 probably part of some larger data structure or computation that was already
  598 synchronized.  Therefore requiring that all map operations grab a mutex would slow
  599 down most programs and add safety to few.  This was not an easy decision,
  600 however, since it means uncontrolled map access can crash the program.
  601 </p>
  603 <p>
  604 The language does not preclude atomic map updates.  When required, such
  605 as when hosting an untrusted program, the implementation could interlock
  606 map access.
  607 </p>
  609 <p>
  610 Map access is unsafe only when updates are occurring.
  611 As long as all goroutines are only reading—looking up elements in the map,
  612 including iterating through it using a
  613 <code>for</code> <code>range</code> loop—and not changing the map
  614 by assigning to elements or doing deletions,
  615 it is safe for them to access the map concurrently without synchronization.
  616 </p>
  618 <p>
  619 As an aid to correct map use, some implementations of the language
  620 contain a special check that automatically reports at run time when a map is modified
  621 unsafely by concurrent execution.
  622 </p>
  624 <h3 id="language_changes">
  625 Will you accept my language change?</h3>
  627 <p>
  628 People often suggest improvements to the language—the
  629 <a href="//groups.google.com/group/golang-nuts">mailing list</a>
  630 contains a rich history of such discussions—but very few of these changes have
  631 been accepted.
  632 </p>
  634 <p>
  635 Although Go is an open source project, the language and libraries are protected
  636 by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents
  637 changes that break existing programs, at least at the source code level
  638 (programs may need to be recompiled occasionally to stay current).
  639 If your proposal violates the Go 1 specification we cannot even entertain the
  640 idea, regardless of its merit.
  641 A future major release of Go may be incompatible with Go 1, but discussions
  642 on that topic have only just begun and one thing is certain:
  643 there will be very few such incompatibilities introduced in the process.
  644 Moreover, the compatibility promise encourages us to provide an automatic path
  645 forward for old programs to adapt should that situation arise.
  646 </p>
  648 <p>
  649 Even if your proposal is compatible with the Go 1 spec, it might
  650 not be in the spirit of Go's design goals.
  651 The article <i><a href="//talks.golang.org/2012/splash.article">Go
  652 at Google: Language Design in the Service of Software Engineering</a></i>
  653 explains Go's origins and the motivation behind its design.
  654 </p>
  656 <h2 id="types">Types</h2>
  658 <h3 id="Is_Go_an_object-oriented_language">
  659 Is Go an object-oriented language?</h3>
  661 <p>
  662 Yes and no. Although Go has types and methods and allows an
  663 object-oriented style of programming, there is no type hierarchy.
  664 The concept of &ldquo;interface&rdquo; in Go provides a different approach that
  665 we believe is easy to use and in some ways more general. There are
  666 also ways to embed types in other types to provide something
  667 analogous&mdash;but not identical&mdash;to subclassing.
  668 Moreover, methods in Go are more general than in C++ or Java:
  669 they can be defined for any sort of data, even built-in types such
  670 as plain, &ldquo;unboxed&rdquo; integers.
  671 They are not restricted to structs (classes).
  672 </p>
  674 <p>
  675 Also, the lack of a type hierarchy makes &ldquo;objects&rdquo; in Go feel much more
  676 lightweight than in languages such as C++ or Java.
  677 </p>
  679 <h3 id="How_do_I_get_dynamic_dispatch_of_methods">
  680 How do I get dynamic dispatch of methods?</h3>
  682 <p>
  683 The only way to have dynamically dispatched methods is through an
  684 interface. Methods on a struct or any other concrete type are always resolved statically.
  685 </p>
  687 <h3 id="inheritance">
  688 Why is there no type inheritance?</h3>
  689 <p>
  690 Object-oriented programming, at least in the best-known languages,
  691 involves too much discussion of the relationships between types,
  692 relationships that often could be derived automatically.  Go takes a
  693 different approach.
  694 </p>
  696 <p>
  697 Rather than requiring the programmer to declare ahead of time that two
  698 types are related, in Go a type automatically satisfies any interface
  699 that specifies a subset of its methods.  Besides reducing the
  700 bookkeeping, this approach has real advantages.  Types can satisfy
  701 many interfaces at once, without the complexities of traditional
  702 multiple inheritance.
  703 Interfaces can be very lightweight&mdash;an interface with
  704 one or even zero methods can express a useful concept.
  705 Interfaces can be added after the fact if a new idea comes along
  706 or for testing&mdash;without annotating the original types.
  707 Because there are no explicit relationships between types
  708 and interfaces, there is no type hierarchy to manage or discuss.
  709 </p>
  711 <p>
  712 It's possible to use these ideas to construct something analogous to
  713 type-safe Unix pipes.  For instance, see how <code>fmt.Fprintf</code>
  714 enables formatted printing to any output, not just a file, or how the
  715 <code>bufio</code> package can be completely separate from file I/O,
  716 or how the <code>image</code> packages generate compressed
  717 image files.  All these ideas stem from a single interface
  718 (<code>io.Writer</code>) representing a single method
  719 (<code>Write</code>).  And that's only scratching the surface.
  720 Go's interfaces have a profound influence on how programs are structured.
  721 </p>
  723 <p>
  724 It takes some getting used to but this implicit style of type
  725 dependency is one of the most productive things about Go.
  726 </p>
  728 <h3 id="methods_on_basics">
  729 Why is <code>len</code> a function and not a method?</h3>
  730 <p>
  731 We debated this issue but decided
  732 implementing <code>len</code> and friends as functions was fine in practice and
  733 didn't complicate questions about the interface (in the Go type sense)
  734 of basic types.
  735 </p>
  737 <h3 id="overloading">
  738 Why does Go not support overloading of methods and operators?</h3>
  739 <p>
  740 Method dispatch is simplified if it doesn't need to do type matching as well.
  741 Experience with other languages told us that having a variety of
  742 methods with the same name but different signatures was occasionally useful
  743 but that it could also be confusing and fragile in practice.  Matching only by name
  744 and requiring consistency in the types was a major simplifying decision
  745 in Go's type system.
  746 </p>
  748 <p>
  749 Regarding operator overloading, it seems more a convenience than an absolute
  750 requirement.  Again, things are simpler without it.
  751 </p>
  753 <h3 id="implements_interface">
  754 Why doesn't Go have "implements" declarations?</h3>
  756 <p>
  757 A Go type satisfies an interface by implementing the methods of that interface,
  758 nothing more.  This property allows interfaces to be defined and used without
  759 needing to modify existing code.  It enables a kind of
  760 <a href="https://en.wikipedia.org/wiki/Structural_type_system">structural typing</a> that
  761 promotes separation of concerns and improves code re-use, and makes it easier
  762 to build on patterns that emerge as the code develops.
  763 The semantics of interfaces is one of the main reasons for Go's nimble,
  764 lightweight feel.
  765 </p>
  767 <p>
  768 See the <a href="#inheritance">question on type inheritance</a> for more detail.
  769 </p>
  771 <h3 id="guarantee_satisfies_interface">
  772 How can I guarantee my type satisfies an interface?</h3>
  774 <p>
  775 You can ask the compiler to check that the type <code>T</code> implements the
  776 interface <code>I</code> by attempting an assignment using the zero value for
  777 <code>T</code> or pointer to <code>T</code>, as appropriate:
  778 </p>
  780 <pre>
  781 type T struct{}
  782 var _ I = T{}       // Verify that T implements I.
  783 var _ I = (*T)(nil) // Verify that *T implements I.
  784 </pre>
  786 <p>
  787 If <code>T</code> (or <code>*T</code>, accordingly) doesn't implement
  788 <code>I</code>, the mistake will be caught at compile time.
  789 </p>
  791 <p>
  792 If you wish the users of an interface to explicitly declare that they implement
  793 it, you can add a method with a descriptive name to the interface's method set.
  794 For example:
  795 </p>
  797 <pre>
  798 type Fooer interface {
  799     Foo()
  800     ImplementsFooer()
  801 }
  802 </pre>
  804 <p>
  805 A type must then implement the <code>ImplementsFooer</code> method to be a
  806 <code>Fooer</code>, clearly documenting the fact and announcing it in
  807 <a href="/cmd/go/#hdr-Show_documentation_for_package_or_symbol">go doc</a>'s output.
  808 </p>
  810 <pre>
  811 type Bar struct{}
  812 func (b Bar) ImplementsFooer() {}
  813 func (b Bar) Foo() {}
  814 </pre>
  816 <p>
  817 Most code doesn't make use of such constraints, since they limit the utility of
  818 the interface idea. Sometimes, though, they're necessary to resolve ambiguities
  819 among similar interfaces.
  820 </p>
  822 <h3 id="t_and_equal_interface">
  823 Why doesn't type T satisfy the Equal interface?</h3>
  825 <p>
  826 Consider this simple interface to represent an object that can compare
  827 itself with another value:
  828 </p>
  830 <pre>
  831 type Equaler interface {
  832     Equal(Equaler) bool
  833 }
  834 </pre>
  836 <p>
  837 and this type, <code>T</code>:
  838 </p>
  840 <pre>
  841 type T int
  842 func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
  843 </pre>
  845 <p>
  846 Unlike the analogous situation in some polymorphic type systems,
  847 <code>T</code> does not implement <code>Equaler</code>.
  848 The argument type of <code>T.Equal</code> is <code>T</code>,
  849 not literally the required type <code>Equaler</code>.
  850 </p>
  852 <p>
  853 In Go, the type system does not promote the argument of
  854 <code>Equal</code>; that is the programmer's responsibility, as
  855 illustrated by the type <code>T2</code>, which does implement
  856 <code>Equaler</code>:
  857 </p>
  859 <pre>
  860 type T2 int
  861 func (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler
  862 </pre>
  864 <p>
  865 Even this isn't like other type systems, though, because in Go <em>any</em>
  866 type that satisfies <code>Equaler</code> could be passed as the
  867 argument to <code>T2.Equal</code>, and at run time we must
  868 check that the argument is of type <code>T2</code>.
  869 Some languages arrange to make that guarantee at compile time.
  870 </p>
  872 <p>
  873 A related example goes the other way:
  874 </p>
  876 <pre>
  877 type Opener interface {
  878    Open() Reader
  879 }
  881 func (t T3) Open() *os.File
  882 </pre>
  884 <p>
  885 In Go, <code>T3</code> does not satisfy <code>Opener</code>,
  886 although it might in another language.
  887 </p>
  889 <p>
  890 While it is true that Go's type system does less for the programmer
  891 in such cases, the lack of subtyping makes the rules about
  892 interface satisfaction very easy to state: are the function's names
  893 and signatures exactly those of the interface?
  894 Go's rule is also easy to implement efficiently.
  895 We feel these benefits offset the lack of
  896 automatic type promotion. Should Go one day adopt some form of polymorphic
  897 typing, we expect there would be a way to express the idea of these
  898 examples and also have them be statically checked.
  899 </p>
  901 <h3 id="convert_slice_of_interface">
  902 Can I convert a []T to an []interface{}?</h3>
  904 <p>
  905 Not directly.
  906 It is disallowed by the language specification because the two types
  907 do not have the same representation in memory.
  908 It is necessary to copy the elements individually to the destination
  909 slice. This example converts a slice of <code>int</code> to a slice of
  910 <code>interface{}</code>:
  911 </p>
  913 <pre>
  914 t := []int{1, 2, 3, 4}
  915 s := make([]interface{}, len(t))
  916 for i, v := range t {
  917     s[i] = v
  918 }
  919 </pre>
  921 <h3 id="convert_slice_with_same_underlying_type">
  922 Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?</h3>
  924 This last line of this code sample does not compile.
  926 <pre>
  927 type T1 int
  928 type T2 int
  929 var t1 T1
  930 var x = T2(t1) // OK
  931 var st1 []T1
  932 var sx = ([]T2)(st1) // NOT OK
  933 </pre>
  935 <p>
  936 In Go, types are closely tied to methods, in that every named type has
  937 a (possibly empty) method set.
  938 The general rule is that you can change the name of the type being
  939 converted (and thus possibly change its method set) but you can't
  940 change the name (and method set) of elements of a composite type.
  941 Go requires you to be explicit about type conversions.
  942 </p>
  944 <h3 id="nil_error">
  945 Why is my nil error value not equal to nil?
  946 </h3>
  948 <p>
  949 Under the covers, interfaces are implemented as two elements, a type <code>T</code>
  950 and a value <code>V</code>.
  951 <code>V</code> is a concrete value such as an <code>int</code>,
  952 <code>struct</code> or pointer, never an interface itself, and has
  953 type <code>T</code>.
  954 For instance, if we store the <code>int</code> value 3 in an interface,
  955 the resulting interface value has, schematically,
  956 (<code>T=int</code>, <code>V=3</code>).
  957 The value <code>V</code> is also known as the interface's
  958 <em>dynamic</em> value,
  959 since a given interface variable might hold different values <code>V</code>
  960 (and corresponding types <code>T</code>)
  961 during the execution of the program.
  962 </p>
  964 <p>
  965 An interface value is <code>nil</code> only if the <code>V</code> and <code>T</code>
  966 are both unset, (<code>T=nil</code>, <code>V</code> is not set),
  967 In particular, a <code>nil</code> interface will always hold a <code>nil</code> type.
  968 If we store a <code>nil</code> pointer of type <code>*int</code> inside
  969 an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer:
  970 (<code>T=*int</code>, <code>V=nil</code>).
  971 Such an interface value will therefore be non-<code>nil</code>
  972 <em>even when the pointer value <code>V</code> inside is</em> <code>nil</code>.
  973 </p>
  975 <p>
  976 This situation can be confusing, and arises when a <code>nil</code> value is
  977 stored inside an interface value such as an <code>error</code> return:
  978 </p>
  980 <pre>
  981 func returnsError() error {
  982     var p *MyError = nil
  983     if bad() {
  984         p = ErrBad
  985     }
  986     return p // Will always return a non-nil error.
  987 }
  988 </pre>
  990 <p>
  991 If all goes well, the function returns a <code>nil</code> <code>p</code>,
  992 so the return value is an <code>error</code> interface
  993 value holding (<code>T=*MyError</code>, <code>V=nil</code>).
  994 This means that if the caller compares the returned error to <code>nil</code>,
  995 it will always look as if there was an error even if nothing bad happened.
  996 To return a proper <code>nil</code> <code>error</code> to the caller,
  997 the function must return an explicit <code>nil</code>:
  998 </p>
 1001 <pre>
 1002 func returnsError() error {
 1003     if bad() {
 1004         return ErrBad
 1005     }
 1006     return nil
 1007 }
 1008 </pre>
 1010 <p>
 1011 It's a good idea for functions
 1012 that return errors always to use the <code>error</code> type in
 1013 their signature (as we did above) rather than a concrete type such
 1014 as <code>*MyError</code>, to help guarantee the error is
 1015 created correctly. As an example,
 1016 <a href="/pkg/os/#Open"><code>os.Open</code></a>
 1017 returns an <code>error</code> even though, if not <code>nil</code>,
 1018 it's always of concrete type
 1019 <a href="/pkg/os/#PathError"><code>*os.PathError</code></a>.
 1020 </p>
 1022 <p>
 1023 Similar situations to those described here can arise whenever interfaces are used.
 1024 Just keep in mind that if any concrete value
 1025 has been stored in the interface, the interface will not be <code>nil</code>.
 1026 For more information, see
 1027 <a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>.
 1028 </p>
 1031 <h3 id="unions">
 1032 Why are there no untagged unions, as in C?</h3>
 1034 <p>
 1035 Untagged unions would violate Go's memory safety
 1036 guarantees.
 1037 </p>
 1039 <h3 id="variant_types">
 1040 Why does Go not have variant types?</h3>
 1042 <p>
 1043 Variant types, also known as algebraic types, provide a way to specify
 1044 that a value might take one of a set of other types, but only those
 1045 types. A common example in systems programming would specify that an
 1046 error is, say, a network error, a security error or an application
 1047 error and allow the caller to discriminate the source of the problem
 1048 by examining the type of the error. Another example is a syntax tree
 1049 in which each node can be a different type: declaration, statement,
 1050 assignment and so on.
 1051 </p>
 1053 <p>
 1054 We considered adding variant types to Go, but after discussion
 1055 decided to leave them out because they overlap in confusing ways
 1056 with interfaces. What would happen if the elements of a variant type
 1057 were themselves interfaces?
 1058 </p>
 1060 <p>
 1061 Also, some of what variant types address is already covered by the
 1062 language. The error example is easy to express using an interface
 1063 value to hold the error and a type switch to discriminate cases.  The
 1064 syntax tree example is also doable, although not as elegantly.
 1065 </p>
 1067 <h3 id="covariant_types">
 1068 Why does Go not have covariant result types?</h3>
 1070 <p>
 1071 Covariant result types would mean that an interface like
 1072 </p>
 1074 <pre>
 1075 type Copyable interface {
 1076     Copy() interface{}
 1077 }
 1078 </pre>
 1080 <p>
 1081 would be satisfied by the method
 1082 </p>
 1084 <pre>
 1085 func (v Value) Copy() Value
 1086 </pre>
 1088 <p>because <code>Value</code> implements the empty interface.
 1089 In Go method types must match exactly, so <code>Value</code> does not
 1090 implement <code>Copyable</code>.
 1091 Go separates the notion of what a
 1092 type does&mdash;its methods&mdash;from the type's implementation.
 1093 If two methods return different types, they are not doing the same thing.
 1094 Programmers who want covariant result types are often trying to
 1095 express a type hierarchy through interfaces.
 1096 In Go it's more natural to have a clean separation between interface
 1097 and implementation.
 1098 </p>
 1100 <h2 id="values">Values</h2>
 1102 <h3 id="conversions">
 1103 Why does Go not provide implicit numeric conversions?</h3>
 1105 <p>
 1106 The convenience of automatic conversion between numeric types in C is
 1107 outweighed by the confusion it causes.  When is an expression unsigned?
 1108 How big is the value?  Does it overflow?  Is the result portable, independent
 1109 of the machine on which it executes?
 1110 It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo;
 1111 are not easy to implement and inconsistent across architectures.
 1112 For reasons of portability, we decided to make things clear and straightforward
 1113 at the cost of some explicit conversions in the code.
 1114 The definition of constants in Go&mdash;arbitrary precision values free
 1115 of signedness and size annotations&mdash;ameliorates matters considerably,
 1116 though.
 1117 </p>
 1119 <p>
 1120 A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
 1121 are distinct types even if <code>int</code> is a 64-bit type.  The <code>int</code>
 1122 type is generic; if you care about how many bits an integer holds, Go
 1123 encourages you to be explicit.
 1124 </p>
 1126 <h3 id="constants">
 1127 How do constants work in Go?</h3>
 1129 <p>
 1130 Although Go is strict about conversion between variables of different
 1131 numeric types, constants in the language are much more flexible.
 1132 Literal constants such as <code>23</code>, <code>3.14159</code>
 1133 and <a href="/pkg/math/#pkg-constants"><code>math.Pi</code></a>
 1134 occupy a sort of ideal number space, with arbitrary precision and
 1135 no overflow or underflow.
 1136 For instance, the value of <code>math.Pi</code> is specified to 63 places
 1137 in the source code, and constant expressions involving the value keep
 1138 precision beyond what a <code>float64</code> could hold.
 1139 Only when the constant or constant expression is assigned to a
 1140 variable&mdash;a memory location in the program&mdash;does
 1141 it become a "computer" number with
 1142 the usual floating-point properties and precision.
 1143 </p>
 1145 <p>
 1146 Also,
 1147 because they are just numbers, not typed values, constants in Go can be
 1148 used more freely than variables, thereby softening some of the awkwardness
 1149 around the strict conversion rules.
 1150 One can write expressions such as
 1151 </p>
 1153 <pre>
 1154 sqrt2 := math.Sqrt(2)
 1155 </pre>
 1157 <p>
 1158 without complaint from the compiler because the ideal number <code>2</code>
 1159 can be converted safely and accurately
 1160 to a <code>float64</code> for the call to <code>math.Sqrt</code>.
 1161 </p>
 1163 <p>
 1164 A blog post titled <a href="https://blog.golang.org/constants">Constants</a>
 1165 explores this topic in more detail.
 1166 </p>
 1168 <h3 id="builtin_maps">
 1169 Why are maps built in?</h3>
 1170 <p>
 1171 The same reason strings are: they are such a powerful and important data
 1172 structure that providing one excellent implementation with syntactic support
 1173 makes programming more pleasant.  We believe that Go's implementation of maps
 1174 is strong enough that it will serve for the vast majority of uses.
 1175 If a specific application can benefit from a custom implementation, it's possible
 1176 to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
 1177 </p>
 1179 <h3 id="map_keys">
 1180 Why don't maps allow slices as keys?</h3>
 1181 <p>
 1182 Map lookup requires an equality operator, which slices do not implement.
 1183 They don't implement equality because equality is not well defined on such types;
 1184 there are multiple considerations involving shallow vs. deep comparison, pointer vs.
 1185 value comparison, how to deal with recursive types, and so on.
 1186 We may revisit this issue&mdash;and implementing equality for slices
 1187 will not invalidate any existing programs&mdash;but without a clear idea of what
 1188 equality of slices should mean, it was simpler to leave it out for now.
 1189 </p>
 1191 <p>
 1192 In Go 1, unlike prior releases, equality is defined for structs and arrays, so such
 1193 types can be used as map keys. Slices still do not have a definition of equality, though.
 1194 </p>
 1196 <h3 id="references">
 1197 Why are maps, slices, and channels references while arrays are values?</h3>
 1198 <p>
 1199 There's a lot of history on that topic.  Early on, maps and channels
 1200 were syntactically pointers and it was impossible to declare or use a
 1201 non-pointer instance.  Also, we struggled with how arrays should work.
 1202 Eventually we decided that the strict separation of pointers and
 1203 values made the language harder to use.  Changing these
 1204 types to act as references to the associated, shared data structures resolved
 1205 these issues. This change added some regrettable complexity to the
 1206 language but had a large effect on usability: Go became a more
 1207 productive, comfortable language when it was introduced.
 1208 </p>
 1210 <h2 id="Writing_Code">Writing Code</h2>
 1212 <h3 id="How_are_libraries_documented">
 1213 How are libraries documented?</h3>
 1215 <p>
 1216 There is a program, <code>godoc</code>, written in Go, that extracts
 1217 package documentation from the source code and serves it as a web
 1218 page with links to declarations, files, and so on.
 1219 An instance is running at
 1220 <a href="/pkg/">golang.org/pkg/</a>.
 1221 In fact, <code>godoc</code> implements the full site at
 1222 <a href="/">golang.org/</a>.
 1223 </p>
 1225 <p>
 1226 A <code>godoc</code> instance may be configured to provide rich,
 1227 interactive static analyses of symbols in the programs it displays; details are
 1228 listed <a href="https://golang.org/lib/godoc/analysis/help.html">here</a>.
 1229 </p>
 1231 <p>
 1232 For access to documentation from the command line, the
 1233 <a href="https://golang.org/pkg/cmd/go/">go</a> tool has a
 1234 <a href="https://golang.org/pkg/cmd/go/#hdr-Show_documentation_for_package_or_symbol">doc</a>
 1235 subcommand that provides a textual interface to the same information.
 1236 </p>
 1238 <h3 id="Is_there_a_Go_programming_style_guide">
 1239 Is there a Go programming style guide?</h3>
 1241 <p>
 1242 There is no explicit style guide, although there is certainly
 1243 a recognizable "Go style".
 1244 </p>
 1246 <p>
 1247 Go has established conventions to guide decisions around
 1248 naming, layout, and file organization.
 1249 The document <a href="effective_go.html">Effective Go</a>
 1250 contains some advice on these topics.
 1251 More directly, the program <code>gofmt</code> is a pretty-printer
 1252 whose purpose is to enforce layout rules; it replaces the usual
 1253 compendium of do's and don'ts that allows interpretation.
 1254 All the Go code in the repository, and the vast majority in the
 1255 open source world, has been run through <code>gofmt</code>.
 1256 </p>
 1258 <p>
 1259 The document titled
 1260 <a href="//golang.org/s/comments">Go Code Review Comments</a>
 1261 is a collection of very short essays about details of Go idiom that are often
 1262 missed by programmers.
 1263 It is a handy reference for people doing code reviews for Go projects.
 1264 </p>
 1266 <h3 id="How_do_I_submit_patches_to_the_Go_libraries">
 1267 How do I submit patches to the Go libraries?</h3>
 1269 <p>
 1270 The library sources are in the <code>src</code> directory of the repository.
 1271 If you want to make a significant change, please discuss on the mailing list before embarking.
 1272 </p>
 1274 <p>
 1275 See the document
 1276 <a href="contribute.html">Contributing to the Go project</a>
 1277 for more information about how to proceed.
 1278 </p>
 1280 <h3 id="git_https">
 1281 Why does "go get" use HTTPS when cloning a repository?</h3>
 1283 <p>
 1284 Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP)
 1285 and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418
 1286 (git) and TCP port 22 (SSH).
 1287 When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by
 1288 default, providing protection against man-in-the-middle, eavesdropping and tampering attacks.
 1289 The <code>go get</code> command therefore uses HTTPS for safety.
 1290 </p>
 1292 <p>
 1293 <code>Git</code> can be configured to authenticate over HTTPS or to use SSH in place of HTTPS.
 1294 To authenticate over HTTPS, you can add a line
 1295 to the <code>$HOME/.netrc</code> file that git consults:
 1296 </p>
 1297 <pre>
 1298 machine github.com login <i>USERNAME</i> password <i>APIKEY</i>
 1299 </pre>
 1300 <p>
 1301 For GitHub accounts, the password can be a
 1302 <a href="https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/">personal access token</a>.
 1303 </p>
 1305 <p>
 1306 <code>Git</code> can also be configured to use SSH in place of HTTPS for URLs matching a given prefix.
 1307 For example, to use SSH for all GitHub access,
 1308 add these lines to your <code>~/.gitconfig</code>:
 1309 </p>
 1310 <pre>
 1311 [url "ssh://git@github.com/"]
 1312     insteadOf = https://github.com/
 1313 </pre>
 1315 <h3 id="get_version">
 1316 How should I manage package versions using "go get"?</h3>
 1318 <p>
 1319 Since the inception of the project, Go has had no explicit concept of package versions,
 1320 but that is changing.
 1321 Versioning is a source of significant complexity, especially in large code bases,
 1322 and it has taken some time to develop an
 1323 approach that works well at scale in a large enough
 1324 variety of situations to be appropriate to supply to all Go users.
 1325 </p>
 1327 <p>
 1328 The Go 1.11 release adds new, experimental support
 1329 for package versioning to the <code>go</code> command,
 1330 in the form of Go modules.
 1331 For more information, see the <a href="/doc/go1.11#modules">Go 1.11 release notes</a>
 1332 and the <a href="/cmd/go#hdr-Modules__module_versions__and_more"><code>go</code> command documentation</a>.
 1333 </p>
 1335 <p>
 1336 Regardless of the actual package management technology,
 1337 "go get" and the larger Go toolchain does provide isolation of
 1338 packages with different import paths.
 1339 For example, the standard library's <code>html/template</code> and <code>text/template</code>
 1340 coexist even though both are "package template".
 1341 This observation leads to some advice for package authors and package users.
 1342 </p>
 1344 <p>
 1345 Packages intended for public use should try to maintain backwards compatibility as they evolve.
 1346 The <a href="/doc/go1compat.html">Go 1 compatibility guidelines</a> are a good reference here:
 1347 don't remove exported names, encourage tagged composite literals, and so on.
 1348 If different functionality is required, add a new name instead of changing an old one.
 1349 If a complete break is required, create a new package with a new import path.
 1350 </p>
 1352 <p>
 1353 If you're using an externally supplied package and worry that it might change in
 1354 unexpected ways, but are not yet using Go modules,
 1355 the simplest solution is to copy it to your local repository.
 1356 This is the approach Google takes internally and is supported by the
 1357 <code>go</code> command through a technique called "vendoring".
 1358 This involves
 1359 storing a copy of the dependency under a new import path that identifies it as a local copy.
 1360 See the <a href="https://golang.org/s/go15vendor">design
 1361 document</a> for details.
 1362 </p>
 1364 <h2 id="Pointers">Pointers and Allocation</h2>
 1366 <h3 id="pass_by_value">
 1367 When are function parameters passed by value?</h3>
 1369 <p>
 1370 As in all languages in the C family, everything in Go is passed by value.
 1371 That is, a function always gets a copy of the
 1372 thing being passed, as if there were an assignment statement assigning the
 1373 value to the parameter.  For instance, passing an <code>int</code> value
 1374 to a function makes a copy of the <code>int</code>, and passing a pointer
 1375 value makes a copy of the pointer, but not the data it points to.
 1376 (See a <a href="/doc/faq#methods_on_values_or_pointers">later
 1377 section</a> for a discussion of how this affects method receivers.)
 1378 </p>
 1380 <p>
 1381 Map and slice values behave like pointers: they are descriptors that
 1382 contain pointers to the underlying map or slice data.  Copying a map or
 1383 slice value doesn't copy the data it points to.  Copying an interface value
 1384 makes a copy of the thing stored in the interface value.  If the interface
 1385 value holds a struct, copying the interface value makes a copy of the
 1386 struct.  If the interface value holds a pointer, copying the interface value
 1387 makes a copy of the pointer, but again not the data it points to.
 1388 </p>
 1390 <p>
 1391 Note that this discussion is about the semantics of the operations.
 1392 Actual implementations may apply optimizations to avoid copying
 1393 as long as the optimizations do not change the semantics.
 1394 </p>
 1396 <h3 id="pointer_to_interface">
 1397 When should I use a pointer to an interface?</h3>
 1399 <p>
 1400 Almost never. Pointers to interface values arise only in rare, tricky situations involving
 1401 disguising an interface value's type for delayed evaluation.
 1402 </p>
 1404 <p>
 1405 It is a common mistake to pass a pointer to an interface value
 1406 to a function expecting an interface. The compiler will complain about this
 1407 error but the situation can still be confusing, because sometimes a
 1408 <a href="#different_method_sets">pointer
 1409 is necessary to satisfy an interface</a>.
 1410 The insight is that although a pointer to a concrete type can satisfy
 1411 an interface, with one exception <em>a pointer to an interface can never satisfy an interface</em>.
 1412 </p>
 1414 <p>
 1415 Consider the variable declaration,
 1416 </p>
 1418 <pre>
 1419 var w io.Writer
 1420 </pre>
 1422 <p>
 1423 The printing function <code>fmt.Fprintf</code> takes as its first argument
 1424 a value that satisfies <code>io.Writer</code>—something that implements
 1425 the canonical <code>Write</code> method. Thus we can write
 1426 </p>
 1428 <pre>
 1429 fmt.Fprintf(w, "hello, world\n")
 1430 </pre>
 1432 <p>
 1433 If however we pass the address of <code>w</code>, the program will not compile.
 1434 </p>
 1436 <pre>
 1437 fmt.Fprintf(&amp;w, "hello, world\n") // Compile-time error.
 1438 </pre>
 1440 <p>
 1441 The one exception is that any value, even a pointer to an interface, can be assigned to
 1442 a variable of empty interface type (<code>interface{}</code>).
 1443 Even so, it's almost certainly a mistake if the value is a pointer to an interface;
 1444 the result can be confusing.
 1445 </p>
 1447 <h3 id="methods_on_values_or_pointers">
 1448 Should I define methods on values or pointers?</h3>
 1450 <pre>
 1451 func (s *MyStruct) pointerMethod() { } // method on pointer
 1452 func (s MyStruct)  valueMethod()   { } // method on value
 1453 </pre>
 1455 <p>
 1456 For programmers unaccustomed to pointers, the distinction between these
 1457 two examples can be confusing, but the situation is actually very simple.
 1458 When defining a method on a type, the receiver (<code>s</code> in the above
 1459 examples) behaves exactly as if it were an argument to the method.
 1460 Whether to define the receiver as a value or as a pointer is the same
 1461 question, then, as whether a function argument should be a value or
 1462 a pointer.
 1463 There are several considerations.
 1464 </p>
 1466 <p>
 1467 First, and most important, does the method need to modify the
 1468 receiver?
 1469 If it does, the receiver <em>must</em> be a pointer.
 1470 (Slices and maps act as references, so their story is a little
 1471 more subtle, but for instance to change the length of a slice
 1472 in a method the receiver must still be a pointer.)
 1473 In the examples above, if <code>pointerMethod</code> modifies
 1474 the fields of <code>s</code>,
 1475 the caller will see those changes, but <code>valueMethod</code>
 1476 is called with a copy of the caller's argument (that's the definition
 1477 of passing a value), so changes it makes will be invisible to the caller.
 1478 </p>
 1480 <p>
 1481 By the way, in Java method receivers are always pointers,
 1482 although their pointer nature is somewhat disguised
 1483 (and there is a proposal to add value receivers to the language).
 1484 It is the value receivers in Go that are unusual.
 1485 </p>
 1487 <p>
 1488 Second is the consideration of efficiency. If the receiver is large,
 1489 a big <code>struct</code> for instance, it will be much cheaper to
 1490 use a pointer receiver.
 1491 </p>
 1493 <p>
 1494 Next is consistency. If some of the methods of the type must have
 1495 pointer receivers, the rest should too, so the method set is
 1496 consistent regardless of how the type is used.
 1497 See the section on <a href="#different_method_sets">method sets</a>
 1498 for details.
 1499 </p>
 1501 <p>
 1502 For types such as basic types, slices, and small <code>structs</code>,
 1503 a value receiver is very cheap so unless the semantics of the method
 1504 requires a pointer, a value receiver is efficient and clear.
 1505 </p>
 1508 <h3 id="new_and_make">
 1509 What's the difference between new and make?</h3>
 1511 <p>
 1512 In short: <code>new</code> allocates memory, while <code>make</code> initializes
 1513 the slice, map, and channel types.
 1514 </p>
 1516 <p>
 1517 See the <a href="/doc/effective_go.html#allocation_new">relevant section
 1518 of Effective Go</a> for more details.
 1519 </p>
 1521 <h3 id="q_int_sizes">
 1522 What is the size of an <code>int</code> on a 64 bit machine?</h3>
 1524 <p>
 1525 The sizes of <code>int</code> and <code>uint</code> are implementation-specific
 1526 but the same as each other on a given platform.
 1527 For portability, code that relies on a particular
 1528 size of value should use an explicitly sized type, like <code>int64</code>.
 1529 On 32-bit machines the compilers use 32-bit integers by default,
 1530 while on 64-bit machines integers have 64 bits.
 1531 (Historically, this was not always true.)
 1532 </p>
 1534 <p>
 1535 On the other hand, floating-point scalars and complex
 1536 types are always sized (there are no <code>float</code> or <code>complex</code> basic types),
 1537 because programmers should be aware of precision when using floating-point numbers.
 1538 The default type used for an (untyped) floating-point constant is <code>float64</code>.
 1539 Thus <code>foo</code> <code>:=</code> <code>3.0</code> declares a variable <code>foo</code>
 1540 of type <code>float64</code>.
 1541 For a <code>float32</code> variable initialized by an (untyped) constant, the variable type
 1542 must be specified explicitly in the variable declaration:
 1543 </p>
 1545 <pre>
 1546 var foo float32 = 3.0
 1547 </pre>
 1549 <p>
 1550 Alternatively, the constant must be given a type with a conversion as in
 1551 <code>foo := float32(3.0)</code>.
 1552 </p>
 1554 <h3 id="stack_or_heap">
 1555 How do I know whether a variable is allocated on the heap or the stack?</h3>
 1557 <p>
 1558 From a correctness standpoint, you don't need to know.
 1559 Each variable in Go exists as long as there are references to it.
 1560 The storage location chosen by the implementation is irrelevant to the
 1561 semantics of the language.
 1562 </p>
 1564 <p>
 1565 The storage location does have an effect on writing efficient programs.
 1566 When possible, the Go compilers will allocate variables that are
 1567 local to a function in that function's stack frame.  However, if the
 1568 compiler cannot prove that the variable is not referenced after the
 1569 function returns, then the compiler must allocate the variable on the
 1570 garbage-collected heap to avoid dangling pointer errors.
 1571 Also, if a local variable is very large, it might make more sense
 1572 to store it on the heap rather than the stack.
 1573 </p>
 1575 <p>
 1576 In the current compilers, if a variable has its address taken, that variable
 1577 is a candidate for allocation on the heap. However, a basic <em>escape
 1578 analysis</em> recognizes some cases when such variables will not
 1579 live past the return from the function and can reside on the stack.
 1580 </p>
 1582 <h3 id="Why_does_my_Go_process_use_so_much_virtual_memory">
 1583 Why does my Go process use so much virtual memory?</h3>
 1585 <p>
 1586 The Go memory allocator reserves a large region of virtual memory as an arena
 1587 for allocations. This virtual memory is local to the specific Go process; the
 1588 reservation does not deprive other processes of memory.
 1589 </p>
 1591 <p>
 1592 To find the amount of actual memory allocated to a Go process, use the Unix
 1593 <code>top</code> command and consult the <code>RES</code> (Linux) or
 1594 <code>RSIZE</code> (macOS) columns.
 1595 <!-- TODO(adg): find out how this works on Windows -->
 1596 </p>
 1598 <h2 id="Concurrency">Concurrency</h2>
 1600 <h3 id="What_operations_are_atomic_What_about_mutexes">
 1601 What operations are atomic? What about mutexes?</h3>
 1603 <p>
 1604 A description of the atomicity of operations in Go can be found in
 1605 the <a href="/ref/mem">Go Memory Model</a> document.
 1606 </p>
 1608 <p>
 1609 Low-level synchronization and atomic primitives are available in the
 1610 <a href="/pkg/sync">sync</a> and
 1611 <a href="/pkg/sync/atomic">sync/atomic</a>
 1612 packages.
 1613 These packages are good for simple tasks such as incrementing
 1614 reference counts or guaranteeing small-scale mutual exclusion.
 1615 </p>
 1617 <p>
 1618 For higher-level operations, such as coordination among
 1619 concurrent servers, higher-level techniques can lead
 1620 to nicer programs, and Go supports this approach through
 1621 its goroutines and channels.
 1622 For instance, you can structure your program so that only one
 1623 goroutine at a time is ever responsible for a particular piece of data.
 1624 That approach is summarized by the original
 1625 <a href="https://www.youtube.com/watch?v=PAAkCSZUG1c">Go proverb</a>,
 1626 </p>
 1628 <p>
 1629 Do not communicate by sharing memory. Instead, share memory by communicating.
 1630 </p>
 1632 <p>
 1633 See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk
 1634 and its <a href="https://blog.golang.org/2010/07/share-memory-by-communicating.html">
 1635 associated article</a> for a detailed discussion of this concept.
 1636 </p>
 1638 <p>
 1639 Large concurrent programs are likely to borrow from both these toolkits.
 1640 </p>
 1642 <h3 id="parallel_slow">
 1643 Why doesn't my program run faster with more CPUs?</h3>
 1645 <p>
 1646 Whether a program runs faster with more CPUs depends on the problem
 1647 it is solving.
 1648 The Go language provides concurrency primitives, such as goroutines
 1649 and channels, but concurrency only enables parallelism
 1650 when the underlying problem is intrinsically parallel.
 1651 Problems that are intrinsically sequential cannot be sped up by adding
 1652 more CPUs, while those that can be broken into pieces that can
 1653 execute in parallel can be sped up, sometimes dramatically.
 1654 </p>
 1656 <p>
 1657 Sometimes adding more CPUs can slow a program down.
 1658 In practical terms, programs that spend more time
 1659 synchronizing or communicating than doing useful computation
 1660 may experience performance degradation when using
 1661 multiple OS threads.
 1662 This is because passing data between threads involves switching
 1663 contexts, which has significant cost, and that cost can increase
 1664 with more CPUs.
 1665 For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a>
 1666 from the Go specification has no significant parallelism although it launches many
 1667 goroutines; increasing the number of threads (CPUs) is more likely to slow it down than
 1668 to speed it up.
 1669 </p>
 1671 <p>
 1672 For more detail on this topic see the talk entitled
 1673 <a href="//blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency
 1674 is not Parallelism</a>.
 1676 <h3 id="number_cpus">
 1677 How can I control the number of CPUs?</h3>
 1679 <p>
 1680 The number of CPUs available simultaneously to executing goroutines is
 1681 controlled by the <code>GOMAXPROCS</code> shell environment variable,
 1682 whose default value is the number of CPU cores available.
 1683 Programs with the potential for parallel execution should therefore
 1684 achieve it by default on a multiple-CPU machine.
 1685 To change the number of parallel CPUs to use,
 1686 set the environment variable or use the similarly-named
 1687 <a href="/pkg/runtime/#GOMAXPROCS">function</a>
 1688 of the runtime package to configure the
 1689 run-time support to utilize a different number of threads.
 1690 Setting it to 1 eliminates the possibility of true parallelism,
 1691 forcing independent goroutines to take turns executing.
 1692 </p>
 1694 <p>
 1695 The runtime can allocate more threads than the value
 1696 of <code>GOMAXPROCS</code> to service multiple outstanding
 1697 I/O requests.
 1698 <code>GOMAXPROCS</code> only affects how many goroutines
 1699 can actually execute at once; arbitrarily more may be blocked
 1700 in system calls.
 1701 </p>
 1703 <p>
 1704 Go's goroutine scheduler is not as good as it needs to be, although it
 1705 has improved over time.
 1706 In the future, it may better optimize its use of OS threads.
 1707 For now, if there are performance issues,
 1708 setting <code>GOMAXPROCS</code> on a per-application basis may help.
 1709 </p>
 1712 <h3 id="no_goroutine_id">
 1713 Why is there no goroutine ID?</h3>
 1715 <p>
 1716 Goroutines do not have names; they are just anonymous workers.
 1717 They expose no unique identifier, name, or data structure to the programmer.
 1718 Some people are surprised by this, expecting the <code>go</code>
 1719 statement to return some item that can be used to access and control
 1720 the goroutine later.
 1721 </p>
 1723 <p>
 1724 The fundamental reason goroutines are anonymous is so that
 1725 the full Go language is available when programming concurrent code.
 1726 By contrast, the usage patterns that develop when threads and goroutines are
 1727 named can restrict what a library using them can do.
 1728 </p>
 1730 <p>
 1731 Here is an illustration of the difficulties.
 1732 Once one names a goroutine and constructs a model around
 1733 it, it becomes special, and one is tempted to associate all computation
 1734 with that goroutine, ignoring the possibility
 1735 of using multiple, possibly shared goroutines for the processing.
 1736 If the <code>net/http</code> package associated per-request
 1737 state with a goroutine,
 1738 clients would be unable to use more goroutines
 1739 when serving a request.
 1740 </p>
 1742 <p>
 1743 Moreover, experience with libraries such as those for graphics systems
 1744 that require all processing to occur on the "main thread"
 1745 has shown how awkward and limiting the approach can be when
 1746 deployed in a concurrent language.
 1747 The very existence of a special thread or goroutine forces
 1748 the programmer to distort the program to avoid crashes
 1749 and other problems caused by inadvertently operating
 1750 on the wrong thread.
 1751 </p>
 1753 <p>
 1754 For those cases where a particular goroutine is truly special,
 1755 the language provides features such as channels that can be
 1756 used in flexible ways to interact with it.
 1757 </p>
 1759 <h2 id="Functions_methods">Functions and Methods</h2>
 1761 <h3 id="different_method_sets">
 1762 Why do T and *T have different method sets?</h3>
 1764 <p>
 1765 As the <a href="/ref/spec#Types">Go specification</a> says,
 1766 the method set of a type <code>T</code> consists of all methods
 1767 with receiver type <code>T</code>,
 1768 while that of the corresponding pointer
 1769 type <code>*T</code> consists of all methods with receiver <code>*T</code> or
 1770 <code>T</code>.
 1771 That means the method set of <code>*T</code>
 1772 includes that of <code>T</code>,
 1773 but not the reverse.
 1774 </p>
 1776 <p>
 1777 This distinction arises because
 1778 if an interface value contains a pointer <code>*T</code>,
 1779 a method call can obtain a value by dereferencing the pointer,
 1780 but if an interface value contains a value <code>T</code>,
 1781 there is no safe way for a method call to obtain a pointer.
 1782 (Doing so would allow a method to modify the contents of
 1783 the value inside the interface, which is not permitted by
 1784 the language specification.)
 1785 </p>
 1787 <p>
 1788 Even in cases where the compiler could take the address of a value
 1789 to pass to the method, if the method modifies the value the changes
 1790 will be lost in the caller.
 1791 As an example, if the <code>Write</code> method of
 1792 <a href="/pkg/bytes/#Buffer"><code>bytes.Buffer</code></a>
 1793 used a value receiver rather than a pointer,
 1794 this code:
 1795 </p>
 1797 <pre>
 1798 var buf bytes.Buffer
 1799 io.Copy(buf, os.Stdin)
 1800 </pre>
 1802 <p>
 1803 would copy standard input into a <i>copy</i> of <code>buf</code>,
 1804 not into <code>buf</code> itself.
 1805 This is almost never the desired behavior.
 1806 </p>
 1808 <h3 id="closures_and_goroutines">
 1809 What happens with closures running as goroutines?</h3>
 1811 <p>
 1812 Some confusion may arise when using closures with concurrency.
 1813 Consider the following program:
 1814 </p>
 1816 <pre>
 1817 func main() {
 1818     done := make(chan bool)
 1820     values := []string{"a", "b", "c"}
 1821     for _, v := range values {
 1822         go func() {
 1823             fmt.Println(v)
 1824             done &lt;- true
 1825         }()
 1826     }
 1828     // wait for all goroutines to complete before exiting
 1829     for _ = range values {
 1830         &lt;-done
 1831     }
 1832 }
 1833 </pre>
 1835 <p>
 1836 One might mistakenly expect to see <code>a, b, c</code> as the output.
 1837 What you'll probably see instead is <code>c, c, c</code>.  This is because
 1838 each iteration of the loop uses the same instance of the variable <code>v</code>, so
 1839 each closure shares that single variable. When the closure runs, it prints the
 1840 value of <code>v</code> at the time <code>fmt.Println</code> is executed,
 1841 but <code>v</code> may have been modified since the goroutine was launched.
 1842 To help detect this and other problems before they happen, run
 1843 <a href="/cmd/go/#hdr-Run_go_tool_vet_on_packages"><code>go vet</code></a>.
 1844 </p>
 1846 <p>
 1847 To bind the current value of <code>v</code> to each closure as it is launched, one
 1848 must modify the inner loop to create a new variable each iteration.
 1849 One way is to pass the variable as an argument to the closure:
 1850 </p>
 1852 <pre>
 1853     for _, v := range values {
 1854         go func(<b>u</b> string) {
 1855             fmt.Println(<b>u</b>)
 1856             done &lt;- true
 1857         }(<b>v</b>)
 1858     }
 1859 </pre>
 1861 <p>
 1862 In this example, the value of <code>v</code> is passed as an argument to the
 1863 anonymous function. That value is then accessible inside the function as
 1864 the variable <code>u</code>.
 1865 </p>
 1867 <p>
 1868 Even easier is just to create a new variable, using a declaration style that may
 1869 seem odd but works fine in Go:
 1870 </p>
 1872 <pre>
 1873     for _, v := range values {
 1874         <b>v := v</b> // create a new 'v'.
 1875         go func() {
 1876             fmt.Println(<b>v</b>)
 1877             done &lt;- true
 1878         }()
 1879     }
 1880 </pre>
 1882 <p>
 1883 This behavior of the language, not defining a new variable for
 1884 each iteration, may have been a mistake in retrospect.
 1885 It may be addressed in a later version but, for compatibility,
 1886 cannot change in Go version 1.
 1887 </p>
 1889 <h2 id="Control_flow">Control flow</h2>
 1891 <h3 id="Does_Go_have_a_ternary_form">
 1892 Why does Go not have the <code>?:</code> operator?</h3>
 1894 <p>
 1895 There is no ternary testing operation in Go.
 1896 You may use the following to achieve the same
 1897 result:
 1898 </p>
 1900 <pre>
 1901 if expr {
 1902     n = trueVal
 1903 } else {
 1904     n = falseVal
 1905 }
 1906 </pre>
 1908 <p>
 1909 The reason <code>?:</code> is absent from Go is that the language's designers
 1910 had seen the operation used too often to create impenetrably complex expressions.
 1911 The <code>if-else</code> form, although longer,
 1912 is unquestionably clearer.
 1913 A language needs only one conditional control flow construct.
 1914 </p>
 1916 <h2 id="Packages_Testing">Packages and Testing</h2>
 1918 <h3 id="How_do_I_create_a_multifile_package">
 1919 How do I create a multifile package?</h3>
 1921 <p>
 1922 Put all the source files for the package in a directory by themselves.
 1923 Source files can refer to items from different files at will; there is
 1924 no need for forward declarations or a header file.
 1925 </p>
 1927 <p>
 1928 Other than being split into multiple files, the package will compile and test
 1929 just like a single-file package.
 1930 </p>
 1932 <h3 id="How_do_I_write_a_unit_test">
 1933 How do I write a unit test?</h3>
 1935 <p>
 1936 Create a new file ending in <code>_test.go</code> in the same directory
 1937 as your package sources. Inside that file, <code>import "testing"</code>
 1938 and write functions of the form
 1939 </p>
 1941 <pre>
 1942 func TestFoo(t *testing.T) {
 1943     ...
 1944 }
 1945 </pre>
 1947 <p>
 1948 Run <code>go test</code> in that directory.
 1949 That script finds the <code>Test</code> functions,
 1950 builds a test binary, and runs it.
 1951 </p>
 1953 <p>See the <a href="/doc/code.html">How to Write Go Code</a> document,
 1954 the <a href="/pkg/testing/"><code>testing</code></a> package
 1955 and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details.
 1956 </p>
 1958 <h3 id="testing_framework">
 1959 Where is my favorite helper function for testing?</h3>
 1961 <p>
 1962 Go's standard <a href="/pkg/testing/"><code>testing</code></a> package makes it easy to write unit tests, but it lacks
 1963 features provided in other language's testing frameworks such as assertion functions.
 1964 An <a href="#assertions">earlier section</a> of this document explained why Go
 1965 doesn't have assertions, and
 1966 the same arguments apply to the use of <code>assert</code> in tests.
 1967 Proper error handling means letting other tests run after one has failed, so
 1968 that the person debugging the failure gets a complete picture of what is
 1969 wrong. It is more useful for a test to report that
 1970 <code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for
 1971 2, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong
 1972 answer for 2 and therefore no more tests were run. The programmer who
 1973 triggers the test failure may not be familiar with the code that fails.
 1974 Time invested writing a good error message now pays off later when the
 1975 test breaks.
 1976 </p>
 1978 <p>
 1979 A related point is that testing frameworks tend to develop into mini-languages
 1980 of their own, with conditionals and controls and printing mechanisms,
 1981 but Go already has all those capabilities; why recreate them?
 1982 We'd rather write tests in Go; it's one fewer language to learn and the
 1983 approach keeps the tests straightforward and easy to understand.
 1984 </p>
 1986 <p>
 1987 If the amount of extra code required to write
 1988 good errors seems repetitive and overwhelming, the test might work better if
 1989 table-driven, iterating over a list of inputs and outputs defined
 1990 in a data structure (Go has excellent support for data structure literals).
 1991 The work to write a good test and good error messages will then be amortized over many
 1992 test cases. The standard Go library is full of illustrative examples, such as in
 1993 <a href="/src/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>.
 1994 </p>
 1996 <h3 id="x_in_std">
 1997 Why isn't <i>X</i> in the standard library?</h3>
 1999 <p>
 2000 The standard library's purpose is to support the runtime, connect to
 2001 the operating system, and provide key functionality that many Go
 2002 programs require, such as formatted I/O and networking.
 2003 It also contains elements important for web programming, including
 2004 cryptography and support for standards like HTTP, JSON, and XML.
 2005 </p>
 2007 <p>
 2008 There is no clear criterion that defines what is included because for
 2009 a long time, this was the <i>only</i> Go library.
 2010 There are criteria that define what gets added today, however.
 2011 </p>
 2013 <p>
 2014 New additions to the standard library are rare and the bar for
 2015 inclusion is high.
 2016 Code included in the standard library bears a large ongoing maintenance cost
 2017 (often borne by those other than the original author),
 2018 is subject to the <a href="/doc/go1compat.html">Go 1 compatibility promise</a>
 2019 (blocking fixes to any flaws in the API),
 2020 and is subject to the Go
 2021 <a href="https://golang.org/s/releasesched">release schedule</a>,
 2022 preventing bug fixes from being available to users quickly.
 2023 </p>
 2025 <p>
 2026 Most new code should live outside of the standard library and be accessible
 2027 via the <a href="/cmd/go/"><code>go</code> tool</a>'s
 2028 <code>go get</code> command.
 2029 Such code can have its own maintainers, release cycle,
 2030 and compatibility guarantees.
 2031 Users can find packages and read their documentation at
 2032 <a href="https://godoc.org/">godoc.org</a>.
 2033 </p>
 2035 <p>
 2036 Although there are pieces in the standard library that don't really belong,
 2037 such as <code>log/syslog</code>, we continue to maintain everything in the
 2038 library because of the Go 1 compatibility promise.
 2039 But we encourage most new code to live elsewhere.
 2040 </p>
 2042 <h2 id="Implementation">Implementation</h2>
 2044 <h3 id="What_compiler_technology_is_used_to_build_the_compilers">
 2045 What compiler technology is used to build the compilers?</h3>
 2047 <p>
 2048 There are several production compilers for Go, and a number of others
 2049 in development for various platforms.
 2050 </p>
 2052 <p>
 2053 The default compiler, <code>gc</code>, is included with the
 2054 Go distribution as part of the support for the <code>go</code>
 2055 command.
 2056 <code>Gc</code> was originally written in C
 2057 because of the difficulties of bootstrapping&mdash;you'd need a Go compiler to
 2058 set up a Go environment.
 2059 But things have advanced and since the Go 1.5 release the compiler has been
 2060 a Go program.
 2061 The compiler was converted from C to Go using automatic translation tools, as
 2062 described in this <a href="/s/go13compiler">design document</a>
 2063 and <a href="https://talks.golang.org/2015/gogo.slide#1">talk</a>.
 2064 Thus the compiler is now "self-hosting", which means we needed to face
 2065 the bootstrapping problem.
 2066 The solution is to have a working Go installation already in place,
 2067 just as one normally has with a working C installation.
 2068 The story of how to bring up a new Go environment from source
 2069 is described <a href="/s/go15bootstrap">here</a> and
 2070 <a href="/doc/install/source">here</a>.
 2071 </p>
 2073 <p>
 2074 <code>Gc</code> is written in Go with a recursive descent parser
 2075 and uses a custom loader, also written in Go but
 2076 based on the Plan 9 loader, to generate ELF/Mach-O/PE binaries.
 2077 </p>
 2079 <p>
 2080 At the beginning of the project we considered using LLVM for
 2081 <code>gc</code> but decided it was too large and slow to meet
 2082 our performance goals.
 2083 More important in retrospect, starting with LLVM would have made it
 2084 harder to introduce some of the ABI and related changes, such as
 2085 stack management, that Go requires but are not part of the standard
 2086 C setup.
 2087 A new <a href="https://go.googlesource.com/gollvm/">LLVM implementation</a>
 2088 is starting to come together now, however.
 2089 </p>
 2091 <p>
 2092 The <code>Gccgo</code> compiler is a front end written in C++
 2093 with a recursive descent parser coupled to the
 2094 standard GCC back end.
 2095 </p>
 2097 <p>
 2098 Go turned out to be a fine language in which to implement a Go compiler,
 2099 although that was not its original goal.
 2100 Not being self-hosting from the beginning allowed Go's design to
 2101 concentrate on its original use case, which was networked servers.
 2102 Had we decided Go should compile itself early on, we might have
 2103 ended up with a language targeted more for compiler construction,
 2104 which is a worthy goal but not the one we had initially.
 2105 </p>
 2107 <p>
 2108 Although <code>gc</code> does not use them (yet?), a native lexer and
 2109 parser are available in the <a href="/pkg/go/"><code>go</code></a> package
 2110 and there is also a native <a href="/pkg/go/types">type checker</a>.
 2111 </p>
 2113 <h3 id="How_is_the_run_time_support_implemented">
 2114 How is the run-time support implemented?</h3>
 2116 <p>
 2117 Again due to bootstrapping issues, the run-time code was originally written mostly in C (with a
 2118 tiny bit of assembler) but it has since been translated to Go
 2119 (except for some assembler bits).
 2120 <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
 2121 The <code>gccgo</code> compiler implements goroutines using
 2122 a technique called segmented stacks,
 2123 supported by recent modifications to the gold linker.
 2124 <code>Gollvm</code> similarly is built on the corresponding
 2125 LLVM infrastructure.
 2126 </p>
 2128 <h3 id="Why_is_my_trivial_program_such_a_large_binary">
 2129 Why is my trivial program such a large binary?</h3>
 2131 <p>
 2132 The linker in the <code>gc</code> toolchain
 2133 creates statically-linked binaries by default.
 2134 All Go binaries therefore include the Go
 2135 runtime, along with the run-time type information necessary to support dynamic
 2136 type checks, reflection, and even panic-time stack traces.
 2137 </p>
 2139 <p>
 2140 A simple C "hello, world" program compiled and linked statically using
 2141 gcc on Linux is around 750 kB, including an implementation of
 2142 <code>printf</code>.
 2143 An equivalent Go program using
 2144 <code>fmt.Printf</code> weighs a couple of megabytes, but that includes
 2145 more powerful run-time support and type and debugging information.
 2146 </p>
 2148 <p>
 2149 A Go program compiled with <code>gc</code> can be linked with
 2150 the <code>-ldflags=-w</code> flag to disable DWARF generation,
 2151 removing debugging information from the binary but with no
 2152 other loss of functionality.
 2153 This can reduce the binary size substantially.
 2154 </p>
 2156 <h3 id="unused_variables_and_imports">
 2157 Can I stop these complaints about my unused variable/import?</h3>
 2159 <p>
 2160 The presence of an unused variable may indicate a bug, while
 2161 unused imports just slow down compilation,
 2162 an effect that can become substantial as a program accumulates
 2163 code and programmers over time.
 2164 For these reasons, Go refuses to compile programs with unused
 2165 variables or imports,
 2166 trading short-term convenience for long-term build speed and
 2167 program clarity.
 2168 </p>
 2170 <p>
 2171 Still, when developing code, it's common to create these situations
 2172 temporarily and it can be annoying to have to edit them out before the
 2173 program will compile.
 2174 </p>
 2176 <p>
 2177 Some have asked for a compiler option to turn those checks off
 2178 or at least reduce them to warnings.
 2179 Such an option has not been added, though,
 2180 because compiler options should not affect the semantics of the
 2181 language and because the Go compiler does not report warnings, only
 2182 errors that prevent compilation.
 2183 </p>
 2185 <p>
 2186 There are two reasons for having no warnings.  First, if it's worth
 2187 complaining about, it's worth fixing in the code.  (And if it's not
 2188 worth fixing, it's not worth mentioning.) Second, having the compiler
 2189 generate warnings encourages the implementation to warn about weak
 2190 cases that can make compilation noisy, masking real errors that
 2191 <em>should</em> be fixed.
 2192 </p>
 2194 <p>
 2195 It's easy to address the situation, though.  Use the blank identifier
 2196 to let unused things persist while you're developing.
 2197 </p>
 2199 <pre>
 2200 import "unused"
 2202 // This declaration marks the import as used by referencing an
 2203 // item from the package.
 2204 var _ = unused.Item  // TODO: Delete before committing!
 2206 func main() {
 2207     debugData := debug.Profile()
 2208     _ = debugData // Used only during debugging.
 2209     ....
 2210 }
 2211 </pre>
 2213 <p>
 2214 Nowadays, most Go programmers use a tool,
 2215 <a href="https://godoc.org/golang.org/x/tools/cmd/goimports">goimports</a>,
 2216 which automatically rewrites a Go source file to have the correct imports,
 2217 eliminating the unused imports issue in practice.
 2218 This program is easily connected to most editors to run automatically when a Go source file is written.
 2219 </p>
 2221 <h3 id="virus">
 2222 Why does my virus-scanning software think my Go distribution or compiled binary is infected?</h3>
 2224 <p>
 2225 This is a common occurrence, especially on Windows machines, and is almost always a false positive.
 2226 Commercial virus scanning programs are often confused by the structure of Go binaries, which
 2227 they don't see as often as those compiled from other languages.
 2228 </p>
 2230 <p>
 2231 If you've just installed the Go distribution and the system reports it is infected, that's certainly a mistake.
 2232 To be really thorough, you can verify the download by comparing the checksum with those on the
 2233 <a href="https://golang.org/dl/">downloads page</a>.
 2234 </p>
 2236 <p>
 2237 In any case, if you believe the report is in error, please report a bug to the supplier of your virus scanner.
 2238 Maybe in time virus scanners can learn to understand Go programs.
 2239 </p>
 2241 <h2 id="Performance">Performance</h2>
 2243 <h3 id="Why_does_Go_perform_badly_on_benchmark_x">
 2244 Why does Go perform badly on benchmark X?</h3>
 2246 <p>
 2247 One of Go's design goals is to approach the performance of C for comparable
 2248 programs, yet on some benchmarks it does quite poorly, including several
 2249 in <a href="https://go.googlesource.com/exp/+/master/shootout/">golang.org/x/exp/shootout</a>.
 2250 The slowest depend on libraries for which versions of comparable performance
 2251 are not available in Go.
 2252 For instance, <a href="https://go.googlesource.com/exp/+/master/shootout/pidigits.go">pidigits.go</a>
 2253 depends on a multi-precision math package, and the C
 2254 versions, unlike Go's, use <a href="https://gmplib.org/">GMP</a> (which is
 2255 written in optimized assembler).
 2256 Benchmarks that depend on regular expressions
 2257 (<a href="https://go.googlesource.com/exp/+/master/shootout/regex-dna.go">regex-dna.go</a>,
 2258 for instance) are essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to
 2259 mature, highly optimized regular expression libraries like PCRE.
 2260 </p>
 2262 <p>
 2263 Benchmark games are won by extensive tuning and the Go versions of most
 2264 of the benchmarks need attention.  If you measure comparable C
 2265 and Go programs
 2266 (<a href="https://go.googlesource.com/exp/+/master/shootout/reverse-complement.go">reverse-complement.go</a>
 2267 is one example), you'll see the two languages are much closer in raw performance
 2268 than this suite would indicate.
 2269 </p>
 2271 <p>
 2272 Still, there is room for improvement. The compilers are good but could be
 2273 better, many libraries need major performance work, and the garbage collector
 2274 isn't fast enough yet. (Even if it were, taking care not to generate unnecessary
 2275 garbage can have a huge effect.)
 2276 </p>
 2278 <p>
 2279 In any case, Go can often be very competitive.
 2280 There has been significant improvement in the performance of many programs
 2281 as the language and tools have developed.
 2282 See the blog post about
 2283 <a href="//blog.golang.org/2011/06/profiling-go-programs.html">profiling
 2284 Go programs</a> for an informative example.
 2286 <h2 id="change_from_c">Changes from C</h2>
 2288 <h3 id="different_syntax">
 2289 Why is the syntax so different from C?</h3>
 2290 <p>
 2291 Other than declaration syntax, the differences are not major and stem
 2292 from two desires.  First, the syntax should feel light, without too
 2293 many mandatory keywords, repetition, or arcana.  Second, the language
 2294 has been designed to be easy to analyze
 2295 and can be parsed without a symbol table.  This makes it much easier
 2296 to build tools such as debuggers, dependency analyzers, automated
 2297 documentation extractors, IDE plug-ins, and so on.  C and its
 2298 descendants are notoriously difficult in this regard.
 2299 </p>
 2301 <h3 id="declarations_backwards">
 2302 Why are declarations backwards?</h3>
 2303 <p>
 2304 They're only backwards if you're used to C. In C, the notion is that a
 2305 variable is declared like an expression denoting its type, which is a
 2306 nice idea, but the type and expression grammars don't mix very well and
 2307 the results can be confusing; consider function pointers.  Go mostly
 2308 separates expression and type syntax and that simplifies things (using
 2309 prefix <code>*</code> for pointers is an exception that proves the rule).  In C,
 2310 the declaration
 2311 </p>
 2312 <pre>
 2313     int* a, b;
 2314 </pre>
 2315 <p>
 2316 declares <code>a</code> to be a pointer but not <code>b</code>; in Go
 2317 </p>
 2318 <pre>
 2319     var a, b *int
 2320 </pre>
 2321 <p>
 2322 declares both to be pointers.  This is clearer and more regular.
 2323 Also, the <code>:=</code> short declaration form argues that a full variable
 2324 declaration should present the same order as <code>:=</code> so
 2325 </p>
 2326 <pre>
 2327     var a uint64 = 1
 2328 </pre>
 2329 <p>
 2330 has the same effect as
 2331 </p>
 2332 <pre>
 2333     a := uint64(1)
 2334 </pre>
 2335 <p>
 2336 Parsing is also simplified by having a distinct grammar for types that
 2337 is not just the expression grammar; keywords such as <code>func</code>
 2338 and <code>chan</code> keep things clear.
 2339 </p>
 2341 <p>
 2342 See the article about
 2343 <a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a>
 2344 for more details.
 2345 </p>
 2347 <h3 id="no_pointer_arithmetic">
 2348 Why is there no pointer arithmetic?</h3>
 2349 <p>
 2350 Safety.  Without pointer arithmetic it's possible to create a
 2351 language that can never derive an illegal address that succeeds
 2352 incorrectly.  Compiler and hardware technology have advanced to the
 2353 point where a loop using array indices can be as efficient as a loop
 2354 using pointer arithmetic.  Also, the lack of pointer arithmetic can
 2355 simplify the implementation of the garbage collector.
 2356 </p>
 2358 <h3 id="inc_dec">
 2359 Why are <code>++</code> and <code>--</code> statements and not expressions?  And why postfix, not prefix?</h3>
 2360 <p>
 2361 Without pointer arithmetic, the convenience value of pre- and postfix
 2362 increment operators drops.  By removing them from the expression
 2363 hierarchy altogether, expression syntax is simplified and the messy
 2364 issues around order of evaluation of <code>++</code> and <code>--</code>
 2365 (consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>)
 2366 are eliminated as well.  The simplification is
 2367 significant.  As for postfix vs. prefix, either would work fine but
 2368 the postfix version is more traditional; insistence on prefix arose
 2369 with the STL, a library for a language whose name contains, ironically, a
 2370 postfix increment.
 2371 </p>
 2373 <h3 id="semicolons">
 2374 Why are there braces but no semicolons? And why can't I put the opening
 2375 brace on the next line?</h3>
 2376 <p>
 2377 Go uses brace brackets for statement grouping, a syntax familiar to
 2378 programmers who have worked with any language in the C family.
 2379 Semicolons, however, are for parsers, not for people, and we wanted to
 2380 eliminate them as much as possible.  To achieve this goal, Go borrows
 2381 a trick from BCPL: the semicolons that separate statements are in the
 2382 formal grammar but are injected automatically, without lookahead, by
 2383 the lexer at the end of any line that could be the end of a statement.
 2384 This works very well in practice but has the effect that it forces a
 2385 brace style.  For instance, the opening brace of a function cannot
 2386 appear on a line by itself.
 2387 </p>
 2389 <p>
 2390 Some have argued that the lexer should do lookahead to permit the
 2391 brace to live on the next line.  We disagree.  Since Go code is meant
 2392 to be formatted automatically by
 2393 <a href="/cmd/gofmt/"><code>gofmt</code></a>,
 2394 <i>some</i> style must be chosen.  That style may differ from what
 2395 you've used in C or Java, but Go is a different language and
 2396 <code>gofmt</code>'s style is as good as any other.  More
 2397 important&mdash;much more important&mdash;the advantages of a single,
 2398 programmatically mandated format for all Go programs greatly outweigh
 2399 any perceived disadvantages of the particular style.
 2400 Note too that Go's style means that an interactive implementation of
 2401 Go can use the standard syntax one line at a time without special rules.
 2402 </p>
 2404 <h3 id="garbage_collection">
 2405 Why do garbage collection?  Won't it be too expensive?</h3>
 2406 <p>
 2407 One of the biggest sources of bookkeeping in systems programs is
 2408 managing the lifetimes of allocated objects.
 2409 In languages such as C in which it is done manually,
 2410 it can consume a significant amount of programmer time and is
 2411 often the cause of pernicious bugs.
 2412 Even in languages like C++ or Rust that provide mechanisms
 2413 to assist, those mechanisms can have a significant effect on the
 2414 design of the software, often adding programming overhead
 2415 of its own.
 2416 We felt it was critical to eliminate such
 2417 programmer overheads, and advances in garbage collection
 2418 technology in the last few years gave us confidence that it
 2419 could be implemented cheaply enough, and with low enough
 2420 latency, that it could be a viable approach for networked
 2421 systems.
 2422 </p>
 2424 <p>
 2425 Much of the difficulty of concurrent programming
 2426 has its roots in the object lifetime problem:
 2427 as objects get passed among threads it becomes cumbersome
 2428 to guarantee they become freed safely.
 2429 Automatic garbage collection makes concurrent code far easier to write.
 2430 Of course, implementing garbage collection in a concurrent environment is
 2431 itself a challenge, but meeting it once rather than in every
 2432 program helps everyone.
 2433 </p>
 2435 <p>
 2436 Finally, concurrency aside, garbage collection makes interfaces
 2437 simpler because they don't need to specify how memory is managed across them.
 2438 </p>
 2440 <p>
 2441 This is not to say that the recent work in languages
 2442 like Rust that bring new ideas to the problem of managing
 2443 resources is misguided; we encourage this work and are excited to see
 2444 how it evolves.
 2445 But Go takes a more traditional approach by addressing
 2446 object lifetimes through
 2447 garbage collection, and garbage collection alone.
 2448 </p>
 2450 <p>
 2451 The current implementation is a mark-and-sweep collector.
 2452 If the machine is a multiprocessor, the collector runs on a separate CPU
 2453 core in parallel with the main program.
 2454 Major work on the collector in recent years has reduced pause times
 2455 often to the sub-millisecond range, even for large heaps,
 2456 all but eliminating one of the major objections to garbage collection
 2457 in networked servers.
 2458 Work continues to refine the algorithm, reduce overhead and
 2459 latency further, and to explore new approaches.
 2460 The 2018
 2461 <a href="https://blog.golang.org/ismmkeynote">ISMM keynote</a>
 2462 by Rick Hudson of the Go team
 2463 describes the progress so far and suggests some future approaches.
 2464 </p>
 2466 <p>
 2467 On the topic of performance, keep in mind that Go gives the programmer
 2468 considerable control over memory layout and allocation, much more than
 2469 is typical in garbage-collected languages. A careful programmer can reduce
 2470 the garbage collection overhead dramatically by using the language well;
 2471 see the article about
 2472 <a href="//blog.golang.org/2011/06/profiling-go-programs.html">profiling
 2473 Go programs</a> for a worked example, including a demonstration of Go's
 2474 profiling tools.
 2475 </p>