UNPKG

@go-len/go-len-runtime-linux

Version:
1,371 lines (1,178 loc) 90.1 kB
<!--{ "Title": "Frequently Asked Questions (FAQ)", "Path": "/doc/faq" }--> <h2 id="Origins">Origins</h2> <h3 id="What_is_the_purpose_of_the_project"> What is the purpose of the project?</h3> <p> At the time of Go's inception, only a decade ago, the programming world was different from today. Production software was usually written in C++ or Java, GitHub did not exist, most computers were not yet multiprocessors, and other than Visual Studio and Eclipse there were few IDEs or other high-level tools available at all, let alone for free on the Internet. </p> <p> Meanwhile, we had become frustrated by the undue complexity required to use the languages we worked with to develop server software. Computers had become enormously quicker since languages such as C, C++ and Java were first developed but the act of programming had not itself advanced nearly as much. Also, it was clear that multiprocessors were becoming universal but most languages offered little help to program them efficiently and safely. </p> <p> We decided to take a step back and think about what major issues were going to dominate software engineering in the years ahead as technology developed, and how a new language might help address them. For instance, the rise of multicore CPUs argued that a language should provide first-class support for some sort of concurrency or parallelism. And to make resource management tractable in a large concurrent program, garbage collection, or at least some sort of safe automatic memory management was required. </p> <p> These considerations led to <a href="https://commandcenter.blogspot.com/2017/09/go-ten-years-and-climbing.html">a series of discussions</a> from which Go arose, first as a set of ideas and desiderata, then as a language. An overarching goal was that Go do more to help the working programmer by enabling tooling, automating mundane tasks such as code formatting, and removing obstacles to working on large code bases. </p> <p> A much more expansive description of the goals of Go and how they are met, or at least approached, is available in the article, <a href="//talks.golang.org/2012/splash.article">Go at Google: Language Design in the Service of Software Engineering</a>. </p> <h3 id="history"> What is the history of the project?</h3> <p> Robert Griesemer, Rob Pike and Ken Thompson started sketching the goals for a new language on the white board on September 21, 2007. Within a few days the goals had settled into a plan to do something and a fair idea of what it would be. Design continued part-time in parallel with unrelated work. By January 2008, Ken had started work on a compiler with which to explore ideas; it generated C code as its output. By mid-year the language had become a full-time project and had settled enough to attempt a production compiler. In May 2008, Ian Taylor independently started on a GCC front end for Go using the draft specification. Russ Cox joined in late 2008 and helped move the language and libraries from prototype to reality. </p> <p> Go became a public open source project on November 10, 2009. Countless people from the community have contributed ideas, discussions, and code. </p> <p> There are now millions of Go programmers—gophers—around the world, and there are more every day. Go's success has far exceeded our expectations. </p> <h3 id="gopher"> What's the origin of the gopher mascot?</h3> <p> The mascot and logo were designed by <a href="https://reneefrench.blogspot.com">Renée French</a>, who also designed <a href="https://9p.io/plan9/glenda.html">Glenda</a>, the Plan 9 bunny. A <a href="https://blog.golang.org/gopher">blog post</a> about the gopher explains how it was derived from one she used for a <a href="https://wfmu.org/">WFMU</a> T-shirt design some years ago. The logo and mascot are covered by the <a href="https://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a> license. </p> <p> The gopher has a <a href="/doc/gopher/modelsheet.jpg">model sheet</a> illustrating his characteristics and how to represent them correctly. The model sheet was first shown in a <a href="https://www.youtube.com/watch?v=4rw_B4yY69k">talk</a> by Renée at Gophercon in 2016. He has unique features; he's the <em>Go gopher</em>, not just any old gopher. </p> <h3 id="go_or_golang"> Is the language called Go or Golang?</h3> <p> The language is called Go. The "golang" moniker arose because the web site is <a href="https://golang.org">golang.org</a>, not go.org, which was not available to us. Many use the golang name, though, and it is handy as a label. For instance, the Twitter tag for the language is "#golang". The language's name is just plain Go, regardless. </p> <p> A side note: Although the <a href="https://blog.golang.org/go-brand">official logo</a> has two capital letters, the language name is written Go, not GO. </p> <h3 id="creating_a_new_language"> Why did you create a new language?</h3> <p> Go was born out of frustration with existing languages and environments for the work we were doing at Google. Programming had become too difficult and the choice of languages was partly to blame. One had to choose either efficient compilation, efficient execution, or ease of programming; all three were not available in the same mainstream language. Programmers who could were choosing ease over safety and efficiency by moving to dynamically typed languages such as Python and JavaScript rather than C++ or, to a lesser extent, Java. </p> <p> We were not alone in our concerns. After many years with a pretty quiet landscape for programming languages, Go was among the first of several new languages—Rust, Elixir, Swift, and more—that have made programming language development an active, almost mainstream field again. </p> <p> Go addressed these issues by attempting to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aimed to be modern, with support for networked and multicore computing. Finally, working with Go is intended to be <i>fast</i>: it should take at most a few seconds to build a large executable on a single computer. To meet these goals required addressing a number of linguistic issues: an expressive but lightweight type system; concurrency and garbage collection; rigid dependency specification; and so on. These cannot be addressed well by libraries or tools; a new language was called for. </p> <p> The article <a href="//talks.golang.org/2012/splash.article">Go at Google</a> discusses the background and motivation behind the design of the Go language, as well as providing more detail about many of the answers presented in this FAQ. </p> <h3 id="ancestors"> What are Go's ancestors?</h3> <p> Go is mostly in the C family (basic syntax), with significant input from the Pascal/Modula/Oberon family (declarations, packages), plus some ideas from languages inspired by Tony Hoare's CSP, such as Newsqueak and Limbo (concurrency). However, it is a new language across the board. In every respect the language was designed by thinking about what programmers do and how to make programming, at least the kind of programming we do, more effective, which means more fun. </p> <h3 id="principles"> What are the guiding principles in the design?</h3> <p> When Go was designed, Java and C++ were the most commonly used languages for writing servers, at least at Google. We felt that these languages required too much bookkeeping and repetition. Some programmers reacted by moving towards more dynamic, fluid languages like Python, at the cost of efficiency and type safety. We felt it should be possible to have the efficiency, the safety, and the fluidity in a single language. </p> <p> Go attempts to reduce the amount of typing in both senses of the word. Throughout its design, we have tried to reduce clutter and complexity. There are no forward declarations and no header files; everything is declared exactly once. Initialization is expressive, automatic, and easy to use. Syntax is clean and light on keywords. Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by simple type derivation using the <code>:=</code> declare-and-initialize construct. And perhaps most radically, there is no type hierarchy: types just <i>are</i>, they don't have to announce their relationships. These simplifications allow Go to be expressive yet comprehensible without sacrificing, well, sophistication. </p> <p> Another important principle is to keep the concepts orthogonal. Methods can be implemented for any type; structures represent data while interfaces represent abstraction; and so on. Orthogonality makes it easier to understand what happens when things combine. </p> <h2 id="Usage">Usage</h2> <h3 id="internal_usage"> Is Google using Go internally?</h3> <p> Yes. Go is used widely in production inside Google. One easy example is the server behind <a href="//golang.org">golang.org</a>. It's just the <a href="/cmd/godoc"><code>godoc</code></a> document server running in a production configuration on <a href="https://developers.google.com/appengine/">Google App Engine</a>. </p> <p> A more significant instance is Google's download server, <code>dl.google.com</code>, which delivers Chrome binaries and other large installables such as <code>apt-get</code> packages. </p> <p> Go is not the only language used at Google, far from it, but it is a key language for a number of areas including <a href="https://talks.golang.org/2013/go-sreops.slide">site reliability engineering (SRE)</a> and large-scale data processing. </p> <h3 id="external_usage"> What other companies use Go?</h3> <p> Go usage is growing worldwide, especially but by no means exclusively in the cloud computing space. A couple of major cloud infrastructure projects written in Go are Docker and Kubernetes, but there are many more. </p> <p> It's not just cloud, though. The Go Wiki includes a <a href="https://github.com/golang/go/wiki/GoUsers">page</a>, updated regularly, that lists some of the many companies using Go. </p> <p> The Wiki also has a page with links to <a href="https://github.com/golang/go/wiki/SuccessStories">success stories</a> about companies and projects that are using the language. </p> <h3 id="Do_Go_programs_link_with_Cpp_programs"> Do Go programs link with C/C++ programs?</h3> <p> It is possible to use C and Go together in the same address space, but it is not a natural fit and can require special interface software. Also, linking C with Go code gives up the memory safety and stack management properties that Go provides. Sometimes it's absolutely necessary to use C libraries to solve a problem, but doing so always introduces an element of risk not present with pure Go code, so do so with care. </p> <p> If you do need to use C with Go, how to proceed depends on the Go compiler implementation. There are three Go compiler implementations supported by the Go team. These are <code>gc</code>, the default compiler, <code>gccgo</code>, which uses the GCC back end, and a somewhat less mature <code>gollvm</code>, which uses the LLVM infrastructure. </p> <p> <code>Gc</code> uses a different calling convention and linker from C and therefore cannot be called directly from C programs, or vice versa. The <a href="/cmd/cgo/"><code>cgo</code></a> program provides the mechanism for a &ldquo;foreign function interface&rdquo; to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries. </p> <p> You can also use <code>cgo</code> and SWIG with <code>Gccgo</code> and <code>gollvm</code>. Since they use a traditional API, it's also possible, with great care, to link code from these compilers directly with GCC/LLVM-compiled C or C++ programs. However, doing so safely requires an understanding of the calling conventions for all languages concerned, as well as concern for stack limits when calling C or C++ from Go. </p> <h3 id="ide"> What IDEs does Go support?</h3> <p> The Go project does not include a custom IDE, but the language and libraries have been designed to make it easy to analyze source code. As a consequence, most well-known editors and IDEs support Go well, either directly or through a plugin. </p> <p> The list of well-known IDEs and editors that have good Go support available includes Emacs, Vim, VSCode, Atom, Eclipse, Sublime, IntelliJ (through a custom variant called Goland), and many more. Chances are your favorite environment is a productive one for programming in Go. </p> <h3 id="protocol_buffers"> Does Go support Google's protocol buffers?</h3> <p> A separate open source project provides the necessary compiler plugin and library. It is available at <a href="//github.com/golang/protobuf">github.com/golang/protobuf/</a>. </p> <h3 id="Can_I_translate_the_Go_home_page"> Can I translate the Go home page into another language?</h3> <p> Absolutely. We encourage developers to make Go Language sites in their own languages. However, if you choose to add the Google logo or branding to your site (it does not appear on <a href="//golang.org/">golang.org</a>), you will need to abide by the guidelines at <a href="//www.google.com/permissions/guidelines.html">www.google.com/permissions/guidelines.html</a> </p> <h2 id="Design">Design</h2> <h3 id="runtime"> Does Go have a runtime?</h3> <p> Go does have an extensive library, called the <em>runtime</em>, that is part of every Go program. The runtime library implements garbage collection, concurrency, stack management, and other critical features of the Go language. Although it is more central to the language, Go's runtime is analogous to <code>libc</code>, the C library. </p> <p> It is important to understand, however, that Go's runtime does not include a virtual machine, such as is provided by the Java runtime. Go programs are compiled ahead of time to native machine code (or JavaScript or WebAssembly, for some variant implementations). Thus, although the term is often used to describe the virtual environment in which a program runs, in Go the word &ldquo;runtime&rdquo; is just the name given to the library providing critical language services. </p> <h3 id="unicode_identifiers"> What's up with Unicode identifiers?</h3> <p> When designing Go, we wanted to make sure that it was not overly ASCII-centric, which meant extending the space of identifiers from the confines of 7-bit ASCII. Go's rule&mdash;identifier characters must be letters or digits as defined by Unicode&mdash;is simple to understand and to implement but has restrictions. Combining characters are excluded by design, for instance, and that excludes some languages such as Devanagari. </p> <p> This rule has one other unfortunate consequence. Since an exported identifier must begin with an upper-case letter, identifiers created from characters in some languages can, by definition, not be exported. For now the only solution is to use something like <code>X日本語</code>, which is clearly unsatisfactory. </p> <p> Since the earliest version of the language, there has been considerable thought into how best to expand the identifier space to accommodate programmers using other native languages. Exactly what to do remains an active topic of discussion, and a future version of the language may be more liberal in its definition of an identifier. For instance, it might adopt some of the ideas from the Unicode organization's <a href="http://unicode.org/reports/tr31/">recommendations</a> for identifiers. Whatever happens, it must be done compatibly while preserving (or perhaps expanding) the way letter case determines visibility of identifiers, which remains one of our favorite features of Go. </p> <p> For the time being, we have a simple rule that can be expanded later without breaking programs, one that avoids bugs that would surely arise from a rule that admits ambiguous identifiers. </p> <h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3> <p> Every language contains novel features and omits someone's favorite feature. Go was designed with an eye on felicity of programming, speed of compilation, orthogonality of concepts, and the need to support features such as concurrency and garbage collection. Your favorite feature may be missing because it doesn't fit, because it affects compilation speed or clarity of design, or because it would make the fundamental system model too difficult. </p> <p> If it bothers you that Go is missing feature <var>X</var>, please forgive us and investigate the features that Go does have. You might find that they compensate in interesting ways for the lack of <var>X</var>. </p> <h3 id="generics"> Why does Go not have generic types?</h3> <p> Generics may well be added at some point. We don't feel an urgency for them, although we understand some programmers do. </p> <p> Go was intended as a language for writing server programs that would be easy to maintain over time. (See <a href="https://talks.golang.org/2012/splash.article">this article</a> for more background.) The design concentrated on things like scalability, readability, and concurrency. Polymorphic programming did not seem essential to the language's goals at the time, and so was left out for simplicity. </p> <p> The language is more mature now, and there is scope to consider some form of generic programming. However, there remain some caveats. </p> <p> Generics are convenient but they come at a cost in complexity in the type system and run-time. We haven't yet found a design that gives value proportionate to the complexity, although we continue to think about it. Meanwhile, Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly. </p> <p> The topic remains open. For a look at several previous unsuccessful attempts to design a good generics solution for Go, see <a href="https://golang.org/issue/15292">this proposal</a>. </p> <h3 id="exceptions"> Why does Go not have exceptions?</h3> <p> We believe that coupling exceptions to a control structure, as in the <code>try-catch-finally</code> idiom, results in convoluted code. It also tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional. </p> <p> Go takes a different approach. For plain error handling, Go's multi-value returns make it easy to report an error without overloading the return value. <a href="/doc/articles/error_handling.html">A canonical error type, coupled with Go's other features</a>, makes error handling pleasant but quite different from that in other languages. </p> <p> Go also has a couple of built-in functions to signal and recover from truly exceptional conditions. The recovery mechanism is executed only as part of a function's state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code. </p> <p> See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details. Also, the <a href="https://blog.golang.org/errors-are-values">Errors are values</a> blog post describes one approach to handling errors cleanly in Go by demonstrating that, since errors are just values, the full power of Go can deployed in error handling. </p> <h3 id="assertions"> Why does Go not have assertions?</h3> <p> Go doesn't provide assertions. They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. Proper error handling means that servers continue to operate instead of crashing after a non-fatal error. Proper error reporting means that errors are direct and to the point, saving the programmer from interpreting a large crash trace. Precise errors are particularly important when the programmer seeing the errors is not familiar with the code. </p> <p> We understand that this is a point of contention. There are many things in the Go language and libraries that differ from modern practices, simply because we feel it's sometimes worth trying a different approach. </p> <h3 id="csp"> Why build concurrency on the ideas of CSP?</h3> <p> Concurrency and multi-threaded programming have over time developed a reputation for difficulty. We believe this is due partly to complex designs such as <a href="https://en.wikipedia.org/wiki/POSIX_Threads">pthreads</a> and partly to overemphasis on low-level details such as mutexes, condition variables, and memory barriers. Higher-level interfaces enable much simpler code, even if there are still mutexes and such under the covers. </p> <p> One of the most successful models for providing high-level linguistic support for concurrency comes from Hoare's Communicating Sequential Processes, or CSP. Occam and Erlang are two well known languages that stem from CSP. Go's concurrency primitives derive from a different part of the family tree whose main contribution is the powerful notion of channels as first class objects. Experience with several earlier languages has shown that the CSP model fits well into a procedural language framework. </p> <h3 id="goroutines"> Why goroutines instead of threads?</h3> <p> Goroutines are part of making concurrency easy to use. The idea, which has been around for a while, is to multiplex independently executing functions&mdash;coroutines&mdash;onto a set of threads. When a coroutine blocks, such as by calling a blocking system call, the run-time automatically moves other coroutines on the same operating system thread to a different, runnable thread so they won't be blocked. The programmer sees none of this, which is the point. The result, which we call goroutines, can be very cheap: they have little overhead beyond the memory for the stack, which is just a few kilobytes. </p> <p> To make the stacks small, Go's run-time uses resizable, bounded stacks. A newly minted goroutine is given a few kilobytes, which is almost always enough. When it isn't, the run-time grows (and shrinks) the memory for storing the stack automatically, allowing many goroutines to live in a modest amount of memory. The CPU overhead averages about three cheap instructions per function call. It is practical to create hundreds of thousands of goroutines in the same address space. If goroutines were just threads, system resources would run out at a much smaller number. </p> <h3 id="atomic_maps"> Why are map operations not defined to be atomic?</h3> <p> After long discussion it was decided that the typical use of maps did not require safe access from multiple goroutines, and in those cases where it did, the map was probably part of some larger data structure or computation that was already synchronized. Therefore requiring that all map operations grab a mutex would slow down most programs and add safety to few. This was not an easy decision, however, since it means uncontrolled map access can crash the program. </p> <p> The language does not preclude atomic map updates. When required, such as when hosting an untrusted program, the implementation could interlock map access. </p> <p> Map access is unsafe only when updates are occurring. As long as all goroutines are only reading—looking up elements in the map, including iterating through it using a <code>for</code> <code>range</code> loop—and not changing the map by assigning to elements or doing deletions, it is safe for them to access the map concurrently without synchronization. </p> <p> As an aid to correct map use, some implementations of the language contain a special check that automatically reports at run time when a map is modified unsafely by concurrent execution. </p> <h3 id="language_changes"> Will you accept my language change?</h3> <p> People often suggest improvements to the language—the <a href="//groups.google.com/group/golang-nuts">mailing list</a> contains a rich history of such discussions—but very few of these changes have been accepted. </p> <p> Although Go is an open source project, the language and libraries are protected by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents changes that break existing programs, at least at the source code level (programs may need to be recompiled occasionally to stay current). If your proposal violates the Go 1 specification we cannot even entertain the idea, regardless of its merit. A future major release of Go may be incompatible with Go 1, but discussions on that topic have only just begun and one thing is certain: there will be very few such incompatibilities introduced in the process. Moreover, the compatibility promise encourages us to provide an automatic path forward for old programs to adapt should that situation arise. </p> <p> Even if your proposal is compatible with the Go 1 spec, it might not be in the spirit of Go's design goals. The article <i><a href="//talks.golang.org/2012/splash.article">Go at Google: Language Design in the Service of Software Engineering</a></i> explains Go's origins and the motivation behind its design. </p> <h2 id="types">Types</h2> <h3 id="Is_Go_an_object-oriented_language"> Is Go an object-oriented language?</h3> <p> Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of &ldquo;interface&rdquo; in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous&mdash;but not identical&mdash;to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, &ldquo;unboxed&rdquo; integers. They are not restricted to structs (classes). </p> <p> Also, the lack of a type hierarchy makes &ldquo;objects&rdquo; in Go feel much more lightweight than in languages such as C++ or Java. </p> <h3 id="How_do_I_get_dynamic_dispatch_of_methods"> How do I get dynamic dispatch of methods?</h3> <p> The only way to have dynamically dispatched methods is through an interface. Methods on a struct or any other concrete type are always resolved statically. </p> <h3 id="inheritance"> Why is there no type inheritance?</h3> <p> Object-oriented programming, at least in the best-known languages, involves too much discussion of the relationships between types, relationships that often could be derived automatically. Go takes a different approach. </p> <p> Rather than requiring the programmer to declare ahead of time that two types are related, in Go a type automatically satisfies any interface that specifies a subset of its methods. Besides reducing the bookkeeping, this approach has real advantages. Types can satisfy many interfaces at once, without the complexities of traditional multiple inheritance. Interfaces can be very lightweight&mdash;an interface with one or even zero methods can express a useful concept. Interfaces can be added after the fact if a new idea comes along or for testing&mdash;without annotating the original types. Because there are no explicit relationships between types and interfaces, there is no type hierarchy to manage or discuss. </p> <p> It's possible to use these ideas to construct something analogous to type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code> enables formatted printing to any output, not just a file, or how the <code>bufio</code> package can be completely separate from file I/O, or how the <code>image</code> packages generate compressed image files. All these ideas stem from a single interface (<code>io.Writer</code>) representing a single method (<code>Write</code>). And that's only scratching the surface. Go's interfaces have a profound influence on how programs are structured. </p> <p> It takes some getting used to but this implicit style of type dependency is one of the most productive things about Go. </p> <h3 id="methods_on_basics"> Why is <code>len</code> a function and not a method?</h3> <p> We debated this issue but decided implementing <code>len</code> and friends as functions was fine in practice and didn't complicate questions about the interface (in the Go type sense) of basic types. </p> <h3 id="overloading"> Why does Go not support overloading of methods and operators?</h3> <p> Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system. </p> <p> Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it. </p> <h3 id="implements_interface"> Why doesn't Go have "implements" declarations?</h3> <p> A Go type satisfies an interface by implementing the methods of that interface, nothing more. This property allows interfaces to be defined and used without needing to modify existing code. It enables a kind of <a href="https://en.wikipedia.org/wiki/Structural_type_system">structural typing</a> that promotes separation of concerns and improves code re-use, and makes it easier to build on patterns that emerge as the code develops. The semantics of interfaces is one of the main reasons for Go's nimble, lightweight feel. </p> <p> See the <a href="#inheritance">question on type inheritance</a> for more detail. </p> <h3 id="guarantee_satisfies_interface"> How can I guarantee my type satisfies an interface?</h3> <p> You can ask the compiler to check that the type <code>T</code> implements the interface <code>I</code> by attempting an assignment using the zero value for <code>T</code> or pointer to <code>T</code>, as appropriate: </p> <pre> type T struct{} var _ I = T{} // Verify that T implements I. var _ I = (*T)(nil) // Verify that *T implements I. </pre> <p> If <code>T</code> (or <code>*T</code>, accordingly) doesn't implement <code>I</code>, the mistake will be caught at compile time. </p> <p> If you wish the users of an interface to explicitly declare that they implement it, you can add a method with a descriptive name to the interface's method set. For example: </p> <pre> type Fooer interface { Foo() ImplementsFooer() } </pre> <p> A type must then implement the <code>ImplementsFooer</code> method to be a <code>Fooer</code>, clearly documenting the fact and announcing it in <a href="/cmd/go/#hdr-Show_documentation_for_package_or_symbol">go doc</a>'s output. </p> <pre> type Bar struct{} func (b Bar) ImplementsFooer() {} func (b Bar) Foo() {} </pre> <p> Most code doesn't make use of such constraints, since they limit the utility of the interface idea. Sometimes, though, they're necessary to resolve ambiguities among similar interfaces. </p> <h3 id="t_and_equal_interface"> Why doesn't type T satisfy the Equal interface?</h3> <p> Consider this simple interface to represent an object that can compare itself with another value: </p> <pre> type Equaler interface { Equal(Equaler) bool } </pre> <p> and this type, <code>T</code>: </p> <pre> type T int func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler </pre> <p> Unlike the analogous situation in some polymorphic type systems, <code>T</code> does not implement <code>Equaler</code>. The argument type of <code>T.Equal</code> is <code>T</code>, not literally the required type <code>Equaler</code>. </p> <p> In Go, the type system does not promote the argument of <code>Equal</code>; that is the programmer's responsibility, as illustrated by the type <code>T2</code>, which does implement <code>Equaler</code>: </p> <pre> type T2 int func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler </pre> <p> Even this isn't like other type systems, though, because in Go <em>any</em> type that satisfies <code>Equaler</code> could be passed as the argument to <code>T2.Equal</code>, and at run time we must check that the argument is of type <code>T2</code>. Some languages arrange to make that guarantee at compile time. </p> <p> A related example goes the other way: </p> <pre> type Opener interface { Open() Reader } func (t T3) Open() *os.File </pre> <p> In Go, <code>T3</code> does not satisfy <code>Opener</code>, although it might in another language. </p> <p> While it is true that Go's type system does less for the programmer in such cases, the lack of subtyping makes the rules about interface satisfaction very easy to state: are the function's names and signatures exactly those of the interface? Go's rule is also easy to implement efficiently. We feel these benefits offset the lack of automatic type promotion. Should Go one day adopt some form of polymorphic typing, we expect there would be a way to express the idea of these examples and also have them be statically checked. </p> <h3 id="convert_slice_of_interface"> Can I convert a []T to an []interface{}?</h3> <p> Not directly. It is disallowed by the language specification because the two types do not have the same representation in memory. It is necessary to copy the elements individually to the destination slice. This example converts a slice of <code>int</code> to a slice of <code>interface{}</code>: </p> <pre> t := []int{1, 2, 3, 4} s := make([]interface{}, len(t)) for i, v := range t { s[i] = v } </pre> <h3 id="convert_slice_with_same_underlying_type"> Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?</h3> This last line of this code sample does not compile. <pre> type T1 int type T2 int var t1 T1 var x = T2(t1) // OK var st1 []T1 var sx = ([]T2)(st1) // NOT OK </pre> <p> In Go, types are closely tied to methods, in that every named type has a (possibly empty) method set. The general rule is that you can change the name of the type being converted (and thus possibly change its method set) but you can't change the name (and method set) of elements of a composite type. Go requires you to be explicit about type conversions. </p> <h3 id="nil_error"> Why is my nil error value not equal to nil? </h3> <p> Under the covers, interfaces are implemented as two elements, a type <code>T</code> and a value <code>V</code>. <code>V</code> is a concrete value such as an <code>int</code>, <code>struct</code> or pointer, never an interface itself, and has type <code>T</code>. For instance, if we store the <code>int</code> value 3 in an interface, the resulting interface value has, schematically, (<code>T=int</code>, <code>V=3</code>). The value <code>V</code> is also known as the interface's <em>dynamic</em> value, since a given interface variable might hold different values <code>V</code> (and corresponding types <code>T</code>) during the execution of the program. </p> <p> An interface value is <code>nil</code> only if the <code>V</code> and <code>T</code> are both unset, (<code>T=nil</code>, <code>V</code> is not set), In particular, a <code>nil</code> interface will always hold a <code>nil</code> type. If we store a <code>nil</code> pointer of type <code>*int</code> inside an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer: (<code>T=*int</code>, <code>V=nil</code>). Such an interface value will therefore be non-<code>nil</code> <em>even when the pointer value <code>V</code> inside is</em> <code>nil</code>. </p> <p> This situation can be confusing, and arises when a <code>nil</code> value is stored inside an interface value such as an <code>error</code> return: </p> <pre> func returnsError() error { var p *MyError = nil if bad() { p = ErrBad } return p // Will always return a non-nil error. } </pre> <p> If all goes well, the function returns a <code>nil</code> <code>p</code>, so the return value is an <code>error</code> interface value holding (<code>T=*MyError</code>, <code>V=nil</code>). This means that if the caller compares the returned error to <code>nil</code>, it will always look as if there was an error even if nothing bad happened. To return a proper <code>nil</code> <code>error</code> to the caller, the function must return an explicit <code>nil</code>: </p> <pre> func returnsError() error { if bad() { return ErrBad } return nil } </pre> <p> It's a good idea for functions that return errors always to use the <code>error</code> type in their signature (as we did above) rather than a concrete type such as <code>*MyError</code>, to help guarantee the error is created correctly. As an example, <a href="/pkg/os/#Open"><code>os.Open</code></a> returns an <code>error</code> even though, if not <code>nil</code>, it's always of concrete type <a href="/pkg/os/#PathError"><code>*os.PathError</code></a>. </p> <p> Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be <code>nil</code>. For more information, see <a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>. </p> <h3 id="unions"> Why are there no untagged unions, as in C?</h3> <p> Untagged unions would violate Go's memory safety guarantees. </p> <h3 id="variant_types"> Why does Go not have variant types?</h3> <p> Variant types, also known as algebraic types, provide a way to specify that a value might take one of a set of other types, but only those types. A common example in systems programming would specify that an error is, say, a network error, a security error or an application error and allow the caller to discriminate the source of the problem by examining the type of the error. Another example is a syntax tree in which each node can be a different type: declaration, statement, assignment and so on. </p> <p> We considered adding variant types to Go, but after discussion decided to leave them out because they overlap in confusing ways with interfaces. What would happen if the elements of a variant type were themselves interfaces? </p> <p> Also, some of what variant types address is already covered by the language. The error example is easy to express using an interface value to hold the error and a type switch to discriminate cases. The syntax tree example is also doable, although not as elegantly. </p> <h3 id="covariant_types"> Why does Go not have covariant result types?</h3> <p> Covariant result types would mean that an interface like </p> <pre> type Copyable interface { Copy() interface{} } </pre> <p> would be satisfied by the method </p> <pre> func (v Value) Copy() Value </pre> <p>because <code>Value</code> implements the empty interface. In Go method types must match exactly, so <code>Value</code> does not implement <code>Copyable</code>. Go separates the notion of what a type does&mdash;its methods&mdash;from the type's implementation. If two methods return different types, they are not doing the same thing. Programmers who want covariant result types are often trying to express a type hierarchy through interfaces. In Go it's more natural to have a clean separation between interface and implementation. </p> <h2 id="values">Values</h2> <h3 id="conversions"> Why does Go not provide implicit numeric conversions?</h3> <p> The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes? It also complicates the compiler; &ldquo;the usual arithmetic conversions&rdquo; are not easy to implement and inconsistent across architectures. For reasons of portability, we decided to make things clear and straightforward at the cost of some explicit conversions in the code. The definition of constants in Go&mdash;arbitrary precision values free of signedness and size annotations&mdash;ameliorates matters considerably, though. </p> <p> A related detail is that, unlike in C, <code>int</code> and <code>int64</code> are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code> type is generic; if you care about how many bits an integer holds, Go encourages you to be explicit. </p> <h3 id="constants"> How do constants work in Go?</h3> <p> Although Go is strict about conversion between variables of different numeric types, constants in the language are much more flexible. Literal constants such as <code>23</code>, <code>3.14159</code> and <a href="/pkg/math/#pkg-constants"><code>math.Pi</code></a> occupy a sort of ideal number space, with arbitrary precision and no overflow or underflow. For instance, the value of <code>math.Pi</code> is specified to 63 places in the source code, and constant expressions involving the value keep precision beyond what a <code>float64</code> could hold. Only when the constant or constant expression is assigned to a variable&mdash;a memory location in the program&mdash;does it become a "computer" number with the usual floating-point properties and precision. </p> <p> Also, because they are just numbers, not typed values, constants in Go can be used more freely than variables, thereby softening some of the awkwardness around the strict conversion rules. One can write expressions such as </p> <pre> sqrt2 := math.Sqrt(2) </pre> <p> without complaint from the compiler because the ideal number <code>2</code> can be converted safely and accurately to a <code>float64</code> for the call to <code>math.Sqrt</code>. </p> <p> A blog post titled <a href="https://blog.golang.org/constants">Constants</a> explores this topic in more detail. </p> <h3 id="builtin_maps"> Why are maps built in?</h3> <p> The same reason strings are: they are such a powerful and important data structure that providing one excellent implementation with syntactic support makes programming more pleasant. We believe that Go's implementation of maps is strong enough that it will serve for the vast majority of uses. If a specific application can benefit from a custom implementation, it's possible to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff. </p> <h3 id="map_keys"> Why don't maps allow slices as keys?</h3> <p> Map lookup requires an equality operator, which slices do not implement. They don't implement equality because equality is not well defined on such types; there are multiple considerations involving shallow vs. deep comparison, pointer vs. value comparison, how to deal with recursive types, and so on. We may revisit this issue&mdash;and implementing equality for slices will not invalidate any existing programs&mdash;but without a clear idea of what equality of slices should mean, it was simpler to leave it out for now. </p> <p> In Go 1, unlike prior releases, equality is defined for structs and arrays, so such types can be used as map keys. Slices still do not have a definition of equality, though. </p> <h3 id="references"> Why are maps, slices, and channels references while arrays are values?</h3> <p> There's a lot of history on that topic. Early on, maps and channels were syntactically pointers and it was impossible to declare or use a non-pointer instance. Also, we struggled with how arrays should work. Eventually we decided that the strict separation of pointers and values made the language harder to use. Changing these types to act as references to the associated, shared data structures resolved these issues. This change added some regrettable complexity to the language but had a large effect on usability: Go became a more productive, comfortable language when it was introduced. </p> <h2 id="Writing_Code">Writing Code</h2> <h3 id="How_are_libraries_documented"> How are libraries documented?</h3> <p> There is a program, <code>godoc</code>, written in Go, that extracts package documentation from the source code and serves it as a web page with links to declarations, files, and so on. An instance is running at <a href="/pkg/">golang.org/pkg/</a>. In fact, <code>godoc</code> implements the full site at <a href="/">golang.org/</a>. </p> <p> A <code>godoc</code> instance may be configured to provide rich, interactive static analyses of symbols in the programs it displays; details are listed <a href="https://golang.org/lib/godoc/analysis/help.html">here</a>. </p> <p> For access to documentation from the command line, the <a href="https://golang.org/pkg/cmd/go/">go</a> tool has a <a href="https://golang.org/pkg/cmd/go/#hdr-Show_documentation_for_package_or_symbol">doc</a> subcommand that provides a textual interface to the same information. </p> <h3 id="Is_there_a_Go_programming_style_guide"> Is there a Go programming style guide?</h3> <p> There is no explicit style guide, although there is certainly a recognizable "Go style". </p> <p> Go has established conventions to guide decisions around naming, layout, and file organization. The document <a href="effective_go.html">Effective Go</a> contains some advice on these topics. More directly, the program <code>gofmt</code> is a pretty-printer whose purpose is to enforce layout rules; it replaces the usual compendium of do's and don'ts that allows interpretation. All the Go code in the repository, and the vast majority in the open source world, has been run through <code>gofmt</code>. </p> <p> The document titled <a href="//golang.org/s/comments">Go Code Review Comments</a> is a collection of very short essays about details of Go idiom that are often missed by programmers. It is a handy reference for people doing code reviews for Go projects. </p> <h3 id="How_do_I_submit_patches_to_the_Go_libraries"> How do I submit patches to the Go libraries?</h3> <p> The library sources are in the <code>src</code> directory of the repository. If you want to make a significant change, please discuss on the mailing list before embarking. </p> <p> See the document <a href="contribute.html">Contributing to the Go project</a> for more information about how to proceed. </p> <h3 id="git_https"> Why does "go get" use HTTPS when cloning a repository?</h3> <p> Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP) and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 (git) and TCP port 22 (SSH). When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by default, providing protection against man-in-the-middle, eavesdropping and tampering attacks. The <code>go get</code> command therefore uses HTTPS for safety. </p> <p> <code>Git</code> can be configured to authenticate over HTTPS or to use SSH in place of HTTPS. To authenticate over HTTPS, you can add a line to the <code>$HOME/.netrc</code> file that git consults: </p> <pre> machine github.com login <i>USERNAME</i> password <i>APIKEY</i> </pre> <p> For GitHub accounts, the password can be a <a href="https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/">personal access token</a>. </p> <p> <code>Git</code> can also be configured to use SSH in place of HTTPS for URLs matching a given prefix. For example, to use SSH for all GitHub access, add these lines to your <code>~/.gitconfig</code>: </p> <pre> [url "ssh://git@github.com/"] insteadOf = https://github.com/ </pre> <h3 id="get_version"> How should I manage package versions using "go get"?</h3> <p> Since the inception of the project, Go has had no explicit concept of package versions, but that is changing. Versioning is a source of significant complexity, especially in large code bases, and it has taken some time to develop an approach that works well at scale in a large enough variety of situations to be appropriate to supply to all Go users. </p> <p> The Go 1.11 release adds new, experimental support for package versioning to the <code>go</code> command, in the form of Go modules. For more information, see the <a href="/doc/go1.11#modules">Go 1.11 release notes</a> and the <a href="/cmd/go#hdr-Modules__module_versions__and_more"><code>go</code> command documentation</a>. </p> <p> Regardless of the actual package management technology, "go get" and the larger Go toolchain does provide isolation of packages with different import paths. For example, the standard library's <code>html/template</code> and <code>text/template</code> coexist even though both are "package template". This observation leads to some advice for package authors and package users. </p> <p> Packages intended for public use should try to maintain backwards compatibility as they evolve. The <a href="/doc/go1compat.html">Go 1 compatibility guidelines</a> are a good reference here: don't remove exported names, encourage tagged composite literals, and so on. If different functionality is required, add a new name instead of changing an old one. If a complete break is required, create a new package with a new import path. </p> <p> If you're using an externally supplied package and worry that it might change in unexpected ways, but are not yet using Go modules, the simplest solution is to copy it to your local repository. This is the approach Google takes internally and is supported by the <code>go</code> command through a technique called "vendoring". This involves storing a copy of the dependency under a new import path that identifies it as a local copy. See the <a href="https://golang.org/s/go15vendor">design document</a> for details. </p> <h2 id="Pointers">Pointers and Allocation</h2> <h3 id="pass_by_value"> When are function parameters passed by value?</h3> <p> As in all languages in the C family, everything in Go is passed by value. That is