Movatterモバイル変換


[0]ホーム

URL:


  1. Documentation
  2. Frequently Asked Questions (FAQ)

Frequently Asked Questions (FAQ)

Origins

What is the purpose of the project?

At the time of Go’s inception in 2007 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 availableat all, let alone for free on the Internet.

Meanwhile, we had become frustrated by the undue complexity requiredto build large software projects withthe languages we were using and their associated build systems.Computers had become enormously quicker since languages such asC, C++ and Java were first developed but the act of programming had notitself advanced nearly as much.Also, it was clear that multiprocessors were becoming universal butmost languages offered little help to program them efficientlyand safely.

We decided to take a step back and think about what major issues weregoing to dominate software engineering in the years ahead as technologydeveloped, and how a new language might help address them.For instance, the rise of multicore CPUs argued that a language shouldprovide 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.

These considerations led toa series of discussionsfrom which Go arose, first as a set of ideas anddesiderata, then as a language.An overarching goal was that Go do more to help the working programmerby enabling tooling, automating mundane tasks such as code formatting,and removing obstacles to working on large code bases.

A much more expansive description of the goals of Go and howthey are met, or at least approached, is available in the article,Go at Google: Language Design in the Service of Software Engineering.

What is the history of the project?

Robert Griesemer, Rob Pike and Ken Thompson started sketching thegoals 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 somethingand a fair idea of what it would be. Design continued part-time inparallel with unrelated work. By January 2008, Ken had started workon a compiler with which to explore ideas; it generated C code as itsoutput. By mid-year the language had become a full-time project andhad settled enough to attempt a production compiler. In May 2008,Ian Taylor independently started on a GCC front end for Go using thedraft specification. Russ Cox joined in late 2008 and helped move the languageand libraries from prototype to reality.

Go became a public open source project on November 10, 2009.Countless people from the community have contributed ideas, discussions, and code.

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.

What’s the origin of the gopher mascot?

The mascot and logo were designed byRenée French, who also designedGlenda,the Plan 9 bunny.Ablog postabout the gopher explains how it wasderived from one she used for aWFMUT-shirt design some years ago.The logo and mascot are covered by theCreative Commons Attribution 4.0license.

The gopher has amodel sheetillustrating his characteristics and how to represent them correctly.The model sheet was first shown in atalkby Renée at Gophercon in 2016.He has unique features; he’s theGo gopher, not just any old gopher.

Is the language called Go or Golang?

The language is called Go.The “golang” moniker arose because the web site wasoriginallygolang.org.(There was no.dev domain then.)Many use the golang name, though, and it is handy asa label.For instance, the social media tag for the language is “#golang”.The language’s name is just plain Go, regardless.

A side note: Although theofficial logohas two capital letters, the language name is written Go, not GO.

Why did you create a new language?

Go was born out of frustration with existing languages andenvironments for the work we were doing at Google.Programming had become toodifficult and the choice of languages was partly to blame. One had tochoose either efficient compilation, efficient execution, or ease ofprogramming; all three were not available in the same mainstreamlanguage. Programmers who could were choosing ease oversafety and efficiency by moving to dynamically typed languages such asPython and JavaScript rather than C++ or, to a lesser extent, Java.

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 developmentan active, almost mainstream field again.

Go addressed these issues by attempting to combine the ease of programming of an interpreted,dynamically typedlanguage with the efficiency and safety of a statically typed, compiled language.It also aimed to be better adapted to current hardware, with support for networked and multicorecomputing.Finally, working with Go is intended to befast: it should takeat most a few seconds to build a large executable on a single computer.Meeting these goals led us to rethink some of the programming approachesfrom our current languages, leading to:a compositional rather than hierarchical type system;support for concurrency and garbage collection; rigid specification of dependencies;and so on.These cannot be handled well by libraries or tools; a newlanguage was called for.

The articleGo at Googlediscusses 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.

What are Go’s ancestors?

Go is mostly in the C family (basic syntax),with significant input from the Pascal/Modula/Oberonfamily (declarations, packages),plus some ideas from languagesinspired 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 thinkingabout what programmers do and how to make programming, at least thekind of programming we do, more effective, which means more fun.

What are the guiding principles in the design?

When Go was designed, Java and C++ were the most commonlyused languages for writing servers, at least at Google.We felt that these languages requiredtoo much bookkeeping and repetition.Some programmers reacted by moving towards more dynamic,fluid languages like Python, at the cost of efficiency andtype safety.We felt it should be possible to have the efficiency,the safety, and the fluidity in a single language.

Go attempts to reduce the amount of typing in both senses of the word.Throughout its design, we have tried to reduce clutter andcomplexity. 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.Repetition (foo.Foo* myFoo = new(foo.Foo)) is reduced bysimple type derivation using the:=declare-and-initialize construct. And perhaps most radically, thereis no type hierarchy: types justare, they don’t have toannounce their relationships. These simplifications allow Go to beexpressive yet comprehensible without sacrificing productivity.

Another important principle is to keep the concepts orthogonal.Methods can be implemented for any type; structures represent data whileinterfaces represent abstraction; and so on. Orthogonality makes iteasier to understand what happens when things combine.

Usage

Is Google using Go internally?

Yes. Go is used widely in production inside Google.One example is Google’s download server,dl.google.com,which delivers Chrome binaries and other large installables such asapt-getpackages.

Go is not the only language used at Google, far from it, but it is a key languagefor a number of areas includingsite reliability engineering (SRE)and large-scale data processing.It is also a key part of the software that runs Google Cloud.

What other companies use Go?

Go usage is growing worldwide, especially but by no means exclusivelyin the cloud computing space.A couple of major cloud infrastructure projects written in Go areDocker and Kubernetes,but there are many more.

It’s not just cloud, though, as you can see from the list ofcompanies on thego.dev web sitealong with somesuccess stories.Also, the Go Wiki includes apage,updated regularly, that lists some of the many companies using Go.

The Wiki also has a page with links to moresuccess storiesabout companies and projects that are using the language.

Do Go programs link with C/C++ programs?

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 memorysafety 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 withpure Go code, so do so with care.

If you do need to use C with Go, how to proceed depends on the Gocompiler implementation.The “standard” compiler, part of the Go toolchain supported by theGo team at Google, is calledgc.In addition, there are also a GCC-based compiler (gccgo) andan LLVM-based compiler (gollvm),as well as a growing list of unusual ones serving different purposes,sometimes implementing language subsets,such asTinyGo.

Gc uses a different calling convention and linker from C andtherefore cannot be called directly from C programs, or vice versa.Thecgo program provides the mechanism for a“foreign function interface” to allow safe calling ofC libraries from Go code.SWIG extends this capability to C++ libraries.

You can also usecgo and SWIG withgccgo andgollvm.Since they use a traditional ABI, 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 forall languages concerned, as well as concern for stack limits when calling C or C++from Go.

What IDEs does Go support?

The Go project does not include a custom IDE, but the language andlibraries 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.

The Go team also supports a Go language server for the LSP protocol, calledgopls.Tools that support LSP can usegopls to integrate language-specific support.

The list of well-known IDEs and editors that offer good Go supportincludes 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 forprogramming in Go.

Does Go support Google’s protocol buffers?

A separate open source project provides the necessary compiler plugin and library.It is available atgithub.com/golang/protobuf/.

Design

Does Go have a runtime?

Go has an extensive runtime library, often just called theruntime,that is part of every Go program.This 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 analogoustolibc, the C library.

It is important to understand, however, that Go’s runtime does notinclude 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 virtualenvironment in which a program runs, in Go the word “runtime”is just the name given to the library providing critical language services.

What’s up with Unicode identifiers?

When designing Go, we wanted to make sure that it was notoverly ASCII-centric,which meant extending the space of identifiers from theconfines of 7-bit ASCII.Go’s rule—identifier characters must beletters or digits as defined by Unicode—is simple to understandand to implement but has restrictions.Combining characters areexcluded by design, for instance,and that excludes some languages such as Devanagari.

This rule has one other unfortunate consequence.Since an exported identifier must begin with anupper-case letter, identifiers created from charactersin some languages can, by definition, not be exported.For now theonly solution is to use something likeX日本語, whichis clearly unsatisfactory.

Since the earliest version of the language, there has been considerablethought into how best to expand the identifier space to accommodateprogrammers using other native languages.Exactly what to do remains an active topic of discussion, and a futureversion of the language may be more liberal in its definitionof an identifier.For instance, it might adopt some of the ideas from the Unicodeorganization’srecommendationsfor identifiers.Whatever happens, it must be done compatibly while preserving(or perhaps expanding) the way letter case determines visibility ofidentifiers, which remains one of our favorite features of Go.

For the time being, we have a simple rule that can be expanded laterwithout breaking programs, one that avoids bugs that would surely arisefrom a rule that admits ambiguous identifiers.

Why does Go not have feature X?

Every language contains novel features and omits someone’s favoritefeature. Go was designed with an eye on felicity of programming, speed ofcompilation, orthogonality of concepts, and the need to support featuressuch as concurrency and garbage collection. Your favorite feature may bemissing because it doesn’t fit, because it affects compilation speed orclarity of design, or because it would make the fundamental system modeltoo difficult.

If it bothers you that Go is missing featureX,please forgive us and investigate the features that Go does have. You might find thatthey compensate in interesting ways for the lack ofX.

When did Go get generic types?

The Go 1.18 release added type parameters to the language.This permits a form of polymorphic or generic programming.See thelanguage spec and theproposal for details.

Why was Go initially released without generic types?

Go was intended as a language for writing server programs that would beeasy to maintain over time.(Seethis article for more background.)The design concentrated on things like scalability, readability, andconcurrency.Polymorphic programming did not seem essential to the language’sgoals at the time, and so was initially left out for simplicity.

Generics are convenient but they come at a cost in complexity in thetype system and run-time.It took a while to develop a design that we believe gives valueproportionate to the complexity.

Why does Go not have exceptions?

We believe that coupling exceptions to a controlstructure, as in thetry-catch-finally idiom, results inconvoluted code. It also tends to encourage programmers to labeltoo many ordinary errors, such as failing to open a file, asexceptional.

Go takes a different approach. For plain error handling, Go’s multi-valuereturns make it easy to report an error without overloading the return value.A canonical error type, coupled with Go’s other features,makes error handling pleasant but quite differentfrom that in other languages.

Go also has a coupleof built-in functions to signal and recover from truly exceptionalconditions. The recovery mechanism is executed only as part of afunction’s state being torn down after an error, which is sufficientto handle catastrophe but requires no extra control structures and,when used well, can result in clean error-handling code.

See theDefer, Panic, and Recover article for details.Also, theErrors are values blog postdescribes one approach to handling errors cleanly in Go by demonstrating that,since errors are just values, the full power of Go can be deployed in error handling.

Why does Go not have assertions?

Go doesn’t provide assertions. They are undeniably convenient, but ourexperience has been that programmers use them as a crutch to avoid thinkingabout proper error handling and reporting. Proper error handling means thatservers 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. Preciseerrors are particularly important when the programmer seeing the errors isnot familiar with the code.

We understand that this is a point of contention. There are many things inthe Go language and libraries that differ from modern practices, simplybecause we feel it’s sometimes worth trying a different approach.

Why build concurrency on the ideas of CSP?

Concurrency and multi-threaded programming have over timedeveloped a reputation for difficulty. We believe this is due partly to complexdesigns such aspthreadsand partly to overemphasis on low-level detailssuch as mutexes, condition variables, and memory barriers.Higher-level interfaces enable much simpler code, even if there are stillmutexes and such under the covers.

One of the most successful models for providing high-level linguistic supportfor 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 treewhose main contribution is the powerful notion of channels as first class objects.Experience with several earlier languages has shown that the CSP modelfits well into a procedural language framework.

Why goroutines instead of threads?

Goroutines are part of making concurrency easy to use. The idea, which hasbeen around for a while, is to multiplex independently executingfunctions—coroutines—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 operatingsystem 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 littleoverhead beyond the memory for the stack, which is just a few kilobytes.

To make the stacks small, Go’s run-time uses resizable, bounded stacks. A newlyminted goroutine is given a few kilobytes, which is almost always enough.When it isn’t, the run-time grows (and shrinks) the memory for storingthe stack automatically, allowing many goroutines to live in a modestamount 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 sameaddress space.If goroutines were just threads, system resources wouldrun out at a much smaller number.

Why are map operations not defined to be atomic?

After long discussion it was decided that the typical use of maps did not requiresafe access from multiple goroutines, and in those cases where it did, the map wasprobably part of some larger data structure or computation that was alreadysynchronized. Therefore requiring that all map operations grab a mutex would slowdown most programs and add safety to few. This was not an easy decision,however, since it means uncontrolled map access can crash the program.

The language does not preclude atomic map updates. When required, suchas when hosting an untrusted program, the implementation could interlockmap access.

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 aforrange loop—and not changing the mapby assigning to elements or doing deletions,it is safe for them to access the map concurrently without synchronization.

As an aid to correct map use, some implementations of the languagecontain a special check that automatically reports at run time when a map is modifiedunsafely by concurrent execution.Also there is a type in the sync library calledsync.Map that workswell for certain usage patterns such as static caches, although it is notsuitable as a general replacement for the builtin map type.

Will you accept my language change?

People often suggest improvements to the language—themailing listcontains a rich history of such discussions—but very few of these changes havebeen accepted.

Although Go is an open source project, the language and libraries are protectedby acompatibility promise that preventschanges 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 theidea, regardless of its merit.A future major release of Go may be incompatible with Go 1, but discussionson 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 pathforward for old programs to adapt should that situation arise.

Even if your proposal is compatible with the Go 1 spec, it mightnot be in the spirit of Go’s design goals.The articleGoat Google: Language Design in the Service of Software Engineeringexplains Go’s origins and the motivation behind its design.

Types

Is Go an object-oriented language?

Yes and no. Although Go has types and methods and allows anobject-oriented style of programming, there is no type hierarchy.The concept of “interface” in Go provides a different approach thatwe believe is easy to use and in some ways more general. There arealso ways to embed types in other types to provide somethinganalogous—but not identical—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 suchas plain, “unboxed” integers.They are not restricted to structs (classes).

Also, the lack of a type hierarchy makes “objects” in Go feel much morelightweight than in languages such as C++ or Java.

How do I get dynamic dispatch of methods?

The only way to have dynamically dispatched methods is through aninterface. Methods on a struct or any other concrete type are always resolved statically.

Why is there no type inheritance?

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 adifferent approach.

Rather than requiring the programmer to declare ahead of time that twotypes are related, in Go a type automatically satisfies any interfacethat specifies a subset of its methods. Besides reducing thebookkeeping, this approach has real advantages. Types can satisfymany interfaces at once, without the complexities of traditionalmultiple inheritance.Interfaces can be very lightweight—an interface withone or even zero methods can express a useful concept.Interfaces can be added after the fact if a new idea comes alongor for testing—without annotating the original types.Because there are no explicit relationships between typesand interfaces, there is no type hierarchy to manage or discuss.

It’s possible to use these ideas to construct something analogous totype-safe Unix pipes. For instance, see howfmt.Fprintfenables formatted printing to any output, not just a file, or how thebufio package can be completely separate from file I/O,or how theimage packages generate compressedimage files. All these ideas stem from a single interface(io.Writer) representing a single method(Write). And that’s only scratching the surface.Go’s interfaces have a profound influence on how programs are structured.

It takes some getting used to but this implicit style of typedependency is one of the most productive things about Go.

Why islen a function and not a method?

We debated this issue but decidedimplementinglen and friends as functions was fine in practice anddidn’t complicate questions about the interface (in the Go type sense)of basic types.

Why does Go not support overloading of methods and operators?

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 ofmethods with the same name but different signatures was occasionally usefulbut that it could also be confusing and fragile in practice. Matching only by nameand requiring consistency in the types was a major simplifying decisionin Go’s type system.

Regarding operator overloading, it seems more a convenience than an absoluterequirement. Again, things are simpler without it.

Why doesn’t Go have “implements” declarations?

A Go type implements an interface by implementing the methods of that interface,nothing more. This property allows interfaces to be defined and used withoutneeding to modify existing code. It enables a kind ofstructural typing thatpromotes separation of concerns and improves code re-use, and makes it easierto 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.

See thequestion on type inheritance for more detail.

How can I guarantee my type satisfies an interface?

You can ask the compiler to check that the typeT implements theinterfaceI by attempting an assignment using the zero value forT or pointer toT, as appropriate:

type T struct{}var _ I = T{}       // Verify that T implements I.var _ I = (*T)(nil) // Verify that *T implements I.

IfT (or*T, accordingly) doesn’t implementI, the mistake will be caught at compile time.

If you wish the users of an interface to explicitly declare that they implementit, you can add a method with a descriptive name to the interface’s method set.For example:

type Fooer interface {    Foo()    ImplementsFooer()}

A type must then implement theImplementsFooer method to be aFooer, clearly documenting the fact and announcing it ingo doc’s output.

type Bar struct{}func (b Bar) ImplementsFooer() {}func (b Bar) Foo() {}

Most code doesn’t make use of such constraints, since they limit the utility ofthe interface idea. Sometimes, though, they’re necessary to resolve ambiguitiesamong similar interfaces.

Why doesn’t type T satisfy the Equal interface?

Consider this simple interface to represent an object that can compareitself with another value:

type Equaler interface {    Equal(Equaler) bool}

and this type,T:

type T intfunc (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler

Unlike the analogous situation in some polymorphic type systems,T does not implementEqualer.The argument type ofT.Equal isT,not literally the required typeEqualer.

In Go, the type system does not promote the argument ofEqual; that is the programmer’s responsibility, asillustrated by the typeT2, which does implementEqualer:

type T2 intfunc (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler

Even this isn’t like other type systems, though, because in Goanytype that satisfiesEqualer could be passed as theargument toT2.Equal, and at run time we mustcheck that the argument is of typeT2.Some languages arrange to make that guarantee at compile time.

A related example goes the other way:

type Opener interface {   Open() Reader}func (t T3) Open() *os.File

In Go,T3 does not satisfyOpener,although it might in another language.

While it is true that Go’s type system does less for the programmerin such cases, the lack of subtyping makes the rules aboutinterface satisfaction very easy to state: are the function’s namesand signatures exactly those of the interface?Go’s rule is also easy to implement efficiently.We feel these benefits offset the lack ofautomatic type promotion.

Can I convert a []T to an []interface{}?

Not directly.It is disallowed by the language specification because the two typesdo not have the same representation in memory.It is necessary to copy the elements individually to the destinationslice. This example converts a slice ofint to a slice ofinterface{}:

t := []int{1, 2, 3, 4}s := make([]interface{}, len(t))for i, v := range t {    s[i] = v}

Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?

This last line of this code sample does not compile.

type T1 inttype T2 intvar t1 T1var x = T2(t1) // OKvar st1 []T1var sx = ([]T2)(st1) // NOT OK

In Go, types are closely tied to methods, in that every named type hasa (possibly empty) method set.The general rule is that you can change the name of the type beingconverted (and thus possibly change its method set) but you can’tchange the name (and method set) of elements of a composite type.Go requires you to be explicit about type conversions.

Why is my nil error value not equal to nil?

Under the covers, interfaces are implemented as two elements, a typeTand a valueV.V is a concrete value such as anint,struct or pointer, never an interface itself, and hastypeT.For instance, if we store theint value 3 in an interface,the resulting interface value has, schematically,(T=int,V=3).The valueV is also known as the interface’sdynamic value,since a given interface variable might hold different valuesV(and corresponding typesT)during the execution of the program.

An interface value isnil only if theV andTare both unset, (T=nil,V is not set),In particular, anil interface will always hold anil type.If we store anil pointer of type*int insidean interface value, the inner type will be*int regardless of the value of the pointer:(T=*int,V=nil).Such an interface value will therefore be non-nileven when the pointer valueV inside isnil.

This situation can be confusing, and arises when anil value isstored inside an interface value such as anerror return:

func returnsError() error {    var p *MyError = nil    if bad() {        p = ErrBad    }    return p // Will always return a non-nil error.}

If all goes well, the function returns anilp,so the return value is anerror interfacevalue holding (T=*MyError,V=nil).This means that if the caller compares the returned error tonil,it will always look as if there was an error even if nothing bad happened.To return a propernilerror to the caller,the function must return an explicitnil:

func returnsError() error {    if bad() {        return ErrBad    }    return nil}

It’s a good idea for functionsthat return errors always to use theerror type intheir signature (as we did above) rather than a concrete type suchas*MyError, to help guarantee the error iscreated correctly. As an example,os.Openreturns anerror even though, if notnil,it’s always of concrete type*os.PathError.

Similar situations to those described here can arise whenever interfaces are used.Just keep in mind that if any concrete valuehas been stored in the interface, the interface will not benil.For more information, seeThe Laws of Reflection.

Why do zero-size types behave oddly?

Go supports zero-size types, such as a struct with no fields(struct{}) or an array with no elements ([0]byte).There is nothing you can store in a zero-size type, but these typesare sometimes useful when no value is needed, as inmap[int]struct{} or a type that has methods but no value.

Different variables with a zero-size type may be placed at the samelocation in memory.This is safe as no value can be stored in those variables.

Moreover, the language does not make any guarantees as to whetherpointers to two different zero-size variables will compare equal ornot.Such comparisons may even returntrue at one point in the programand then returnfalse at a different point, depending on exactly howthe program is compiled and executed.

A separate issue with zero-size types is that a pointer to a zero-sizestruct field must not overlap with a pointer to a different object inmemory.That could cause confusion in the garbage collector.This means that if the last field in a struct is zero-size, the structwill be padded to ensure that a pointer to the last field does notoverlap with memory that immediately follows the struct.Thus, this program:

func main() {    type S struct {        f1 byte        f2 struct{}    }    fmt.Println(unsafe.Sizeof(S{}))}

will print2, not1, in most Go implementations.

Why are there no untagged unions, as in C?

Untagged unions would violate Go’s memory safetyguarantees.

Why does Go not have variant types?

Variant types, also known as algebraic types, provide a way to specifythat a value might take one of a set of other types, but only thosetypes. A common example in systems programming would specify that anerror is, say, a network error, a security error or an applicationerror and allow the caller to discriminate the source of the problemby examining the type of the error. Another example is a syntax treein which each node can be a different type: declaration, statement,assignment and so on.

We considered adding variant types to Go, but after discussiondecided to leave them out because they overlap in confusing wayswith interfaces. What would happen if the elements of a variant typewere themselves interfaces?

Also, some of what variant types address is already covered by thelanguage. The error example is easy to express using an interfacevalue to hold the error and a type switch to discriminate cases. Thesyntax tree example is also doable, although not as elegantly.

Why does Go not have covariant result types?

Covariant result types would mean that an interface like

type Copyable interface {    Copy() interface{}}

would be satisfied by the method

func (v Value) Copy() Value

becauseValue implements the empty interface.In Go method types must match exactly, soValue does notimplementCopyable.Go separates the notion of what atype does—its methods—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 toexpress a type hierarchy through interfaces.In Go it’s more natural to have a clean separation between interfaceand implementation.

Values

Why does Go not provide implicit numeric conversions?

The convenience of automatic conversion between numeric types in C isoutweighed by the confusion it causes. When is an expression unsigned?How big is the value? Does it overflow? Is the result portable, independentof the machine on which it executes?It also complicates the compiler; C’s “usual arithmetic conversions”are not easy to implement and inconsistent across architectures.For reasons of portability, we decided to make things clear and straightforwardat the cost of some explicit conversions in the code.The definition of constants in Go—arbitrary precision values freeof signedness and size annotations—ameliorates matters considerably,though.

A related detail is that, unlike in C,int andint64are distinct types even ifint is a 64-bit type. Theinttype is generic; if you care about how many bits an integer holds, Goencourages you to be explicit.

How do constants work in Go?

Although Go is strict about conversion between variables of differentnumeric types, constants in the language are much more flexible.Literal constants such as23,3.14159andmath.Pioccupy a sort of ideal number space, with arbitrary precision andno overflow or underflow.For instance, the value ofmath.Pi is specified to 63 decimal digitsin the source code, and constant expressions involving the value keepprecision beyond what afloat64 could hold.Only when the constant or constant expression is assigned to avariable—a memory location in the program—doesit become a “computer” number withthe usual floating-point properties and precision.

Also,because they are just numbers, not typed values, constants in Go can beused more freely than variables, thereby softening some of the awkwardnessaround the strict conversion rules.One can write expressions such as

sqrt2 := math.Sqrt(2)

without complaint from the compiler because the ideal number2can be converted safely and accuratelyto afloat64 for the call tomath.Sqrt.

A blog post titledConstantsexplores this topic in more detail.

Why are maps built in?

The same reason strings are: they are such a powerful and important datastructure that providing one excellent implementation with syntactic supportmakes programming more pleasant. We believe that Go’s implementation of mapsis strong enough that it will serve for the vast majority of uses.If a specific application can benefit from a custom implementation, it’s possibleto write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.

Why don’t maps allow slices as keys?

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—and implementing equality for sliceswill not invalidate any existing programs—but without a clear idea of whatequality of slices should mean, it was simpler to leave it out for now.

Equality is defined for structs and arrays, so they can be used as map keys.

Why are maps, slices, and channels references while arrays are values?

There’s a lot of history on that topic. Early on, maps and channelswere syntactically pointers and it was impossible to declare or use anon-pointer instance. Also, we struggled with how arrays should work.Eventually we decided that the strict separation of pointers andvalues made the language harder to use. Changing thesetypes to act as references to the associated, shared data structures resolvedthese issues. This change added some regrettable complexity to thelanguage but had a large effect on usability: Go became a moreproductive, comfortable language when it was introduced.

Writing Code

How are libraries documented?

For access to documentation from the command line, thego tool has adocsubcommand that provides a textual interface to the documentationfor declarations, files, packages and so on.

The global package discovery pagepkg.go.dev/pkg/.runs a server that extracts package documentation from Go source codeanywhere on the weband serves it as HTML with links to the declarations and related elements.It is the easiest way to learn about existing Go libraries.

In the early days of the project, there was a similar program,godoc,that could also be run to extract documentation for files on the local machine;pkg.go.dev/pkg/ is essentially a descendant.Another descendant is thepkgsitecommand that, likegodoc, can be run locally, althoughit is not yet integrated intothe results shown bygodoc.

Is there a Go programming style guide?

There is no explicit style guide, although there is certainlya recognizable “Go style”.

Go has established conventions to guide decisions aroundnaming, layout, and file organization.The documentEffective Gocontains some advice on these topics.More directly, the programgofmt is a pretty-printerwhose purpose is to enforce layout rules; it replaces the usualcompendium of dos and don’ts that allows interpretation.All the Go code in the repository, and the vast majority in theopen source world, has been run throughgofmt.

The document titledGo Code Review Commentsis a collection of very short essays about details of Go idiom that are oftenmissed by programmers.It is a handy reference for people doing code reviews for Go projects.

How do I submit patches to the Go libraries?

The library sources are in thesrc directory of the repository.If you want to make a significant change, please discuss on the mailing list before embarking.

See the documentContributing to the Go projectfor more information about how to proceed.

Why does “go get” use HTTPS when cloning a repository?

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,git enforces certificate validation bydefault, providing protection against man-in-the-middle, eavesdropping and tampering attacks.Thego get command therefore uses HTTPS for safety.

Git can be configured to authenticate over HTTPS or to use SSH in place of HTTPS.To authenticate over HTTPS, you can add a lineto the$HOME/.netrc file that git consults:

machine github.com login *USERNAME* password *APIKEY*

For GitHub accounts, the password can be apersonal access token.

Git 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~/.gitconfig:

[url "ssh://git@github.com/"]    insteadOf = https://github.com/

When working with private modules, but using a public module proxy for dependencies, you may need to setGOPRIVATE.Seeprivate modules for details and additional settings.

How should I manage package versions using “go get”?

The Go toolchain has a built-in system for managing versioned sets of related packages, known asmodules.Modules were introduced inGo 1.11 and have been ready for production use since1.14.

To create a project using modules, rungo mod init.This command creates ago.mod file that tracks dependency versions.

go mod init example/project

To add, upgrade, or downgrade a dependency, rungo get:

go get golang.org/x/text@v0.3.5

SeeTutorial: Create a module for more information on getting started.

SeeDeveloping modules for guides on managing dependencies with modules.

Packages within modules should maintain backward compatibility as they evolve, following theimport compatibility rule:

If an old package and a new package have the same import path,
the new package must be backwards compatible with the old package.

TheGo 1 compatibility guidelines 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.

Modules codify this withsemantic versioning and semantic import versioning.If a break in compatibility is required, release a module at a new major version.Modules at major version 2 and higher require amajor version suffix as part of their path (like/v2).This preserves the import compatibility rule: packages in different major versions of a module have distinct paths.

Pointers and Allocation

When are function parameters passed by value?

As in all languages in the C family, everything in Go is passed by value.That is, a function always gets a copy of thething being passed, as if there were an assignment statement assigning thevalue to the parameter. For instance, passing anint valueto a function makes a copy of theint, and passing a pointervalue makes a copy of the pointer, but not the data it points to.(See alater sectionfor a discussion of how this affects method receivers.)

Map and slice values behave like pointers: they are descriptors thatcontain pointers to the underlying map or slice data. Copying a map orslice value doesn’t copy the data it points to. Copying an interface valuemakes a copy of the thing stored in the interface value. If the interfacevalue holds a struct, copying the interface value makes a copy of thestruct. If the interface value holds a pointer, copying the interface valuemakes a copy of the pointer, but again not the data it points to.

Note that this discussion is about the semantics of the operations.Actual implementations may apply optimizations to avoid copyingas long as the optimizations do not change the semantics.

When should I use a pointer to an interface?

Almost never. Pointers to interface values arise only in rare, tricky situations involvingdisguising an interface value’s type for delayed evaluation.

It is a common mistake to pass a pointer to an interface valueto a function expecting an interface. The compiler will complain about thiserror but the situation can still be confusing, because sometimes apointeris necessary to satisfy an interface.The insight is that although a pointer to a concrete type can satisfyan interface, with one exceptiona pointer to an interface can never satisfy an interface.

Consider the variable declaration,

var w io.Writer

The printing functionfmt.Fprintf takes as its first argumenta value that satisfiesio.Writer—something that implementsthe canonicalWrite method. Thus we can write

fmt.Fprintf(w, "hello, world\n")

If however we pass the address ofw, the program will not compile.

fmt.Fprintf(&w, "hello, world\n") // Compile-time error.

The one exception is that any value, even a pointer to an interface, can be assigned toa variable of empty interface type (interface{}).Even so, it’s almost certainly a mistake if the value is a pointer to an interface;the result can be confusing.

Should I define methods on values or pointers?

func (s *MyStruct) pointerMethod() { } // method on pointerfunc (s MyStruct)  valueMethod()   { } // method on value

For programmers unaccustomed to pointers, the distinction between thesetwo examples can be confusing, but the situation is actually very simple.When defining a method on a type, the receiver (s in the aboveexamples) behaves exactly as if it were an argument to the method.Whether to define the receiver as a value or as a pointer is the samequestion, then, as whether a function argument should be a value ora pointer.There are several considerations.

First, and most important, does the method need to modify thereceiver?If it does, the receivermust be a pointer.(Slices and maps act as references, so their story is a littlemore subtle, but for instance to change the length of a slicein a method the receiver must still be a pointer.)In the examples above, ifpointerMethod modifiesthe fields ofs,the caller will see those changes, butvalueMethodis called with a copy of the caller’s argument (that’s the definitionof passing a value), so changes it makes will be invisible to the caller.

By the way, in Java method receivers have always been pointers,although their pointer nature is somewhat disguised(and recent developments are bringing value receivers to Java).It is the value receivers in Go that are unusual.

Second is the consideration of efficiency. If the receiver is large,a bigstruct for instance, it may be cheaper touse a pointer receiver.

Next is consistency. If some of the methods of the type must havepointer receivers, the rest should too, so the method set isconsistent regardless of how the type is used.See the section onmethod setsfor details.

For types such as basic types, slices, and smallstructs,a value receiver is very cheap so unless the semantics of the methodrequires a pointer, a value receiver is efficient and clear.

What’s the difference between new and make?

In short:new allocates memory, whilemake initializesthe slice, map, and channel types.

See therelevant sectionof Effective Go for more details.

What is the size of anint on a 64 bit machine?

The sizes ofint anduint are implementation-specificbut the same as each other on a given platform.For portability, code that relies on a particularsize of value should use an explicitly sized type, likeint64.On 32-bit machines the compilers use 32-bit integers by default,while on 64-bit machines integers have 64 bits.(Historically, this was not always true.)

On the other hand, floating-point scalars and complextypes are always sized (there are nofloat orcomplex basic types),because programmers should be aware of precision when using floating-point numbers.The default type used for an (untyped) floating-point constant isfloat64.Thusfoo:=3.0 declares a variablefooof typefloat64.For afloat32 variable initialized by an (untyped) constant, the variable typemust be specified explicitly in the variable declaration:

var foo float32 = 3.0

Alternatively, the constant must be given a type with a conversion as infoo := float32(3.0).

How do I know whether a variable is allocated on the heap or the stack?

From a correctness standpoint, you don’t need to know.Each variable in Go exists as long as there are references to it.The storage location chosen by the implementation is irrelevant to thesemantics of the language.

The storage location does have an effect on writing efficient programs.When possible, the Go compilers will allocate variables that arelocal to a function in that function’s stack frame. However, if thecompiler cannot prove that the variable is not referenced after thefunction returns, then the compiler must allocate the variable on thegarbage-collected heap to avoid dangling pointer errors.Also, if a local variable is very large, it might make more senseto store it on the heap rather than the stack.

In the current compilers, if a variable has its address taken, that variableis a candidate for allocation on the heap. However, a basicescapeanalysis recognizes some cases when such variables will notlive past the return from the function and can reside on the stack.

Why does my Go process use so much virtual memory?

The Go memory allocator reserves a large region of virtual memory as an arenafor allocations. This virtual memory is local to the specific Go process; thereservation does not deprive other processes of memory.

To find the amount of actual memory allocated to a Go process, use the Unixtop command and consult theRES (Linux) orRSIZE (macOS) columns.

Concurrency

What operations are atomic? What about mutexes?

A description of the atomicity of operations in Go can be found intheGo Memory Model document.

Low-level synchronization and atomic primitives are available in thesync andsync/atomicpackages.These packages are good for simple tasks such as incrementingreference counts or guaranteeing small-scale mutual exclusion.

For higher-level operations, such as coordination amongconcurrent servers, higher-level techniques can leadto nicer programs, and Go supports this approach throughits goroutines and channels.For instance, you can structure your program so that only onegoroutine at a time is ever responsible for a particular piece of data.That approach is summarized by the originalGo proverb,

Do not communicate by sharing memory. Instead, share memory by communicating.

See theShare Memory By Communicating code walkand itsassociated articlefor a detailed discussion of this concept.

Large concurrent programs are likely to borrow from both these toolkits.

Why doesn’t my program run faster with more CPUs?

Whether a program runs faster with more CPUs depends on the problemit is solving.The Go language provides concurrency primitives, such as goroutinesand channels, but concurrency only enables parallelismwhen the underlying problem is intrinsically parallel.Problems that are intrinsically sequential cannot be sped up by addingmore CPUs, while those that can be broken into pieces that canexecute in parallel can be sped up, sometimes dramatically.

Sometimes adding more CPUs can slow a program down.In practical terms, programs that spend more timesynchronizing or communicating than doing useful computationmay experience performance degradation when usingmultiple OS threads.This is because passing data between threads involves switchingcontexts, which has significant cost, and that cost can increasewith more CPUs.For instance, theprime sieve examplefrom the Go specification has no significant parallelism although it launches manygoroutines; increasing the number of threads (CPUs) is more likely to slow it down thanto speed it up.

For more detail on this topic see the talk entitledConcurrency is not Parallelism.

How can I control the number of CPUs?

The number of CPUs available simultaneously to executing goroutines iscontrolled by theGOMAXPROCS shell environment variable,whose default value is the number of CPU cores available.Programs with the potential for parallel execution should thereforeachieve it by default on a multiple-CPU machine.To change the number of parallel CPUs to use,set the environment variable or use the similarly-namedfunctionof the runtime package to configure therun-time support to utilize a different number of threads.Setting it to 1 eliminates the possibility of true parallelism,forcing independent goroutines to take turns executing.

The runtime can allocate more threads than the valueofGOMAXPROCS to service multiple outstandingI/O requests.GOMAXPROCS only affects how many goroutinescan actually execute at once; arbitrarily more may be blockedin system calls.

Go’s goroutine scheduler does well at balancing goroutinesand threads, and can even preempt execution of a goroutineto make sure others on the same thread are not starved.However, it is not perfect.If you see performance issues,settingGOMAXPROCS on a per-application basis may help.

Why is there no goroutine ID?

Goroutines do not have names; they are just anonymous workers.They expose no unique identifier, name, or data structure to the programmer.Some people are surprised by this, expecting thegostatement to return some item that can be used to access and controlthe goroutine later.

The fundamental reason goroutines are anonymous is so thatthe full Go language is available when programming concurrent code.By contrast, the usage patterns that develop when threads and goroutines arenamed can restrict what a library using them can do.

Here is an illustration of the difficulties.Once one names a goroutine and constructs a model aroundit, it becomes special, and one is tempted to associate all computationwith that goroutine, ignoring the possibilityof using multiple, possibly shared goroutines for the processing.If thenet/http package associated per-requeststate with a goroutine,clients would be unable to use more goroutineswhen serving a request.

Moreover, experience with libraries such as those for graphics systemsthat require all processing to occur on the “main thread”has shown how awkward and limiting the approach can be whendeployed in a concurrent language.The very existence of a special thread or goroutine forcesthe programmer to distort the program to avoid crashesand other problems caused by inadvertently operatingon the wrong thread.

For those cases where a particular goroutine is truly special,the language provides features such as channels that can beused in flexible ways to interact with it.

Functions and Methods

Why do T and *T have different method sets?

As theGo specification says,the method set of a typeT consists of all methodswith receiver typeT,while that of the corresponding pointertype*T consists of all methods with receiver*T orT.That means the method set of*Tincludes that ofT,but not the reverse.

This distinction arises becauseif an interface value contains a pointer*T,a method call can obtain a value by dereferencing the pointer,but if an interface value contains a valueT,there is no safe way for a method call to obtain a pointer.(Doing so would allow a method to modify the contents ofthe value inside the interface, which is not permitted bythe language specification.)

Even in cases where the compiler could take the address of a valueto pass to the method, if the method modifies the value the changeswill be lost in the caller.

As an example, if the code below were valid:

var buf bytes.Bufferio.Copy(buf, os.Stdin)

it would copy standard input into acopy ofbuf,not intobuf itself.This is almost never the desired behavior and is therefore disallowed by the language.

What happens with closures running as goroutines?

Due to the way loop variables work, before Go version 1.22 (seethe end of this section for an update),some confusion could arise when using closures with concurrency.Consider the following program:

func main() {    done := make(chan bool)    values := []string{"a", "b", "c"}    for _, v := range values {        go func() {            fmt.Println(v)            done <- true        }()    }    // wait for all goroutines to complete before exiting    for _ = range values {        <-done    }}

One might mistakenly expect to seea, b, c as the output.What you’ll probably see instead isc, c, c. This is becauseeach iteration of the loop uses the same instance of the variablev, soeach closure shares that single variable. When the closure runs, it prints thevalue ofv at the timefmt.Println is executed,butv may have been modified since the goroutine was launched.To help detect this and other problems before they happen, rungo vet.

To bind the current value ofv to each closure as it is launched, onemust modify the inner loop to create a new variable each iteration.One way is to pass the variable as an argument to the closure:

    for _, v := range values {        go func(u string) {            fmt.Println(u)            done <- true        }(v)    }

In this example, the value ofv is passed as an argument to theanonymous function. That value is then accessible inside the function asthe variableu.

Even easier is just to create a new variable, using a declaration style that mayseem odd but works fine in Go:

    for _, v := range values {v := v // create a new 'v'.        go func() {            fmt.Println(v)            done <- true        }()    }

This behavior of the language, not defining a new variable foreach iteration, was considered a mistake in retrospect,and has been addressed inGo 1.22, whichdoes indeed create a new variable for each iteration, eliminating this issue.

Control Flow

Why does Go not have the?: operator?

There is no ternary testing operation in Go.You may use the following to achieve the sameresult:

if expr {    n = trueVal} else {    n = falseVal}

The reason?: is absent from Go is that the language’s designershad seen the operation used too often to create impenetrably complex expressions.Theif-else form, although longer,is unquestionably clearer.A language needs only one conditional control flow construct.

Type Parameters

Why does Go have type parameters?

Type parameters permit what is known as generic programming, in whichfunctions and data structures are defined in terms of types that arespecified later, when those functions and data structures are used.For example, they make it possible to write a function that returnsthe minimum of two values of any ordered type, without having to writea separate version for each possible type.For a more in-depth explanation with examples see the blog postWhy Generics?.

How are generics implemented in Go?

The compiler can choose whether to compile each instantiationseparately or whether to compile similar instantiations asa single implementation.The single implementation approach is similar to a function with aninterface parameter.Different compilers will make different choices for different cases.The standard Go compiler ordinarily emits a single instantiationfor every type argument with the same shape, where the shape isdetermined by properties of the type such as the size and the locationof pointers that it contains.Future releases may experiment with the tradeoff between compiletime, run-time efficiency, and code size.

How do generics in Go compare to generics in other languages?

The basic functionality in all languages is similar: it is possible towrite types and functions using types that are specified later.That said, there are some differences.

  • Java

    In Java, the compiler checks generic types at compile time but removesthe types at run time.This is known astype erasure.For example, a Java type known asList<Integer> atcompile time will become the non-generic typeList at runtime.This means, for example, that when using the Java form of typereflection it is impossible to distinguish a value oftypeList<Integer> from a value oftypeList<Float>.In Go the reflection information for a generic type includes the fullcompile-time type information.

    Java uses type wildcards such asList<? extends Number>orList<? super Number> to implement genericcovariance and contravariance.Go does not have these concepts, which makes generic types in Go muchsimpler.

  • C++

    Traditionally C++ templates do not enforce any constraints on typearguments, although C++20 supports optional constraints viaconcepts.In Go constraints are mandatory for all type parameters.C++20 concepts are expressed as small code fragments that must compilewith the type arguments.Go constraints are interface types that define the set of allpermitted type arguments.

    C++ supports template metaprogramming; Go does not.In practice, all C++ compilers compile each template at the pointwhere it is instantiated; as noted above, Go can and does usedifferent approaches for different instantiations.

  • Rust

    The Rust version of constraints is known as trait bounds.In Rust the association between a trait bound and a type must bedefined explicitly, either in the crate that defines the trait boundor the crate that defines the type.In Go type arguments implicitly satisfy constraints, just as Go typesimplicitly implement interface types.The Rust standard library defines standard traits for operations such ascomparison or addition; the Go standard library does not, as these canbe expressed in user code via interface types. The one exceptionis Go’scomparable predefined interface, whichcaptures a property not expressible in the type system.

  • Python

    Python is not a statically typed language, so one can reasonably saythat all Python functions are always generic by default: they canalways be called with values of any type, and any type errors aredetected at run time.

Why does Go use square brackets for type parameter lists?

Java and C++ use angle brackets for type parameter lists, as inJavaList<Integer> and C++std::vector<int>.However, that option was not available for Go, because it leads toa syntactic problem: when parsing code within a function, suchasv := F<T>, at the point of seeingthe< it’s ambiguous whether we are seeing aninstantiation or an expression using the< operator.This is very difficult to resolve without type information.

For example, consider a statement like

    a, b = w < x, y > (z)

Without type information, it is impossible to decide whether the righthand side of the assignment is a pair of expressions (w < xandy > z), or whether it is a generic functioninstantiation and call that returns two result values((w<x, y>)(z)).

It is a key design decision of Go that parsing be possible withouttype information, which seems impossible when using angle brackets forgenerics.

Go is not unique or original in using square brackets; there are otherlanguages such as Scala that also use square brackets for genericcode.

Why does Go not support methods with type parameters?

Go permits a generic type to have methods, but, other than thereceiver, the arguments to those methods cannot use parameterizedtypes.We do not anticipate that Go will ever add generic methods.

The problem is how to implement them.Specifically, consider checking whether a value in aninterface implements another interface with additional methods.For example, consider this type, an empty struct with agenericNop method that returns its argument, for any possible type:

type Empty struct{}func (Empty) Nop[T any](x T) T {    return x}

Now suppose anEmpty value is stored in anany and passedto other code that checks what it can do:

func TryNops(x any) {    if x, ok := x.(interface{ Nop(string) string }); ok {        fmt.Printf("string %s\n", x.Nop("hello"))    }    if x, ok := x.(interface{ Nop(int) int }); ok {        fmt.Printf("int %d\n", x.Nop(42))    }    if x, ok := x.(interface{ Nop(io.Reader) io.Reader }); ok {        data, err := io.ReadAll(x.Nop(strings.NewReader("hello world")))        fmt.Printf("reader %q %v\n", data, err)    }}

How does that code work ifx is anEmpty?It seems thatx must satisfy all three tests,along with any other form with any other type.

What code runs when those methods are called?For non-generic methods, the compiler generates the codefor all method implementations and links them into the final program.But for generic methods, there can be an infinite number of methodimplementations, so a different strategy is needed.

There are four choices:

  1. At link time, make a list of all the possible dynamic interface checks,and then look for types that would satisfy them but are missingcompiled methods, and then reinvoke the compiler to add those methods.

    This would make builds significantly slower, by needing to stop afterlinking and repeat some compilations. It would especially slow downincremental builds. Worse, it is possible that the newly compiled methodcode would itself have new dynamic interface checks, and the processwould have to be repeated. Examples can be constructed wherethe process never even finishes.

  2. Implement some kind of JIT, compiling the needed method code at runtime.

    Go benefits greatly from the simplicity and predictable performanceof being purely ahead-of-time compiled.We are reluctant to take on the complexity of a JIT just to implementone language feature.

  3. Arrange to emit a slow fallback for each generic method that usesa table of functions for every possible language operation on the type parameter,and then use that fallback implementation for the dynamic tests.

    This approach would make a generic method parameterized by anunexpected type much slower than the same methodparameterized by a type observed at compile time.This would make performance much less predictable.

  4. Define that generic methods cannot be used to satisfy interfaces at all.

    Interfaces are an essential part of programming in Go.Disallowing generic methods from satisfying interfaces is unacceptablefrom a design point of view.

None of these choices are good ones, so we chose “none of the above.”

Instead of methods with type parameters, use top-level functions withtype parameters, or add the type parameters to the receiver type.

For more details, including more examples, see theproposal.

Why can’t I use a more specific type for the receiver of a parameterized type?

The method declarations of a generic type are written with a receiverthat includes the type parameter names.Perhaps because of the similarity of the syntax for specifying typesat a call site,some have thought this provides a mechanism for producinga method customized for certain type arguments by naminga specific type in the receiver, such asstring:

type S[T any] struct { f T }func (s S[string]) Add(t string) string {    return s.f + t}

This fails because the wordstring is taken bythe compiler to be the name of the type argument in the method.The compiler error message will be something like “operator + not defined on s.f (variable of type string)”.This can be confusing because the+ operatorworks fine on the predeclared typestring,but the declaration has overwritten, for this method, the definition ofstring,and the operator does not work on that unrelated version ofstring.It’s valid to overwrite a predeclared name like this, but is an odd thing to do andoften a mistake.

Why can’t the compiler infer the type argument in my program?

There are many cases where a programmer can easily see what the typeargument for a generic type or function must be, but the language doesnot permit the compiler to infer it.Type inference is intentionally limited to ensure that there is neverany confusion as to which type is inferred.Experience with other languages suggests that unexpected typeinference can lead to considerable confusion when reading anddebugging a program.It is always possible to specify the explicit type argument to be usedin the call.In the future new forms of inference may be supported, as long as therules remain simple and clear.

Packages and Testing

How do I create a multifile package?

Put all the source files for the package in a directory by themselves.Source files can refer to items from different files at will; there isno need for forward declarations or a header file.

Other than being split into multiple files, the package will compile and testjust like a single-file package.

How do I write a unit test?

Create a new file ending in_test.go in the same directoryas your package sources. Inside that file,import "testing"and write functions of the form

func TestFoo(t *testing.T) {    ...}

Rungo test in that directory.That script finds theTest functions,builds a test binary, and runs it.

See theHow to Write Go Code document,thetesting packageand thego test subcommand for more details.

Where is my favorite helper function for testing?

Go’s standardtesting package makes it easy to write unit tests, but it lacksfeatures provided in other language’s testing frameworks such as assertion functions.Anearlier section of this document explained why Godoesn’t have assertions, andthe same arguments apply to the use ofassert in tests.Proper error handling means letting other tests run after one has failed, sothat the person debugging the failure gets a complete picture of what iswrong. It is more useful for a test to report thatisPrime gives the wrong answer for 2, 3, 5, and 7 (or for2, 4, 8, and 16) than to report thatisPrime gives the wronganswer for 2 and therefore no more tests were run. The programmer whotriggers the test failure may not be familiar with the code that fails.Time invested writing a good error message now pays off later when thetest breaks.

A related point is that testing frameworks tend to develop into mini-languagesof their own, with conditionals and controls and printing mechanisms,but Go already has all those capabilities; why recreate them?We’d rather write tests in Go; it’s one fewer language to learn and theapproach keeps the tests straightforward and easy to understand.

If the amount of extra code required to writegood errors seems repetitive and overwhelming, the test might work better iftable-driven, iterating over a list of inputs and outputs definedin a data structure (Go has excellent support for data structure literals).The work to write a good test and good error messages will then be amortized over manytest cases. The standard Go library is full of illustrative examples, such as inthe formatting tests for thefmt package.

Why isn’tX in the standard library?

The standard library’s purpose is to support the runtime library, connect tothe operating system, and provide key functionality that many Goprograms require, such as formatted I/O and networking.It also contains elements important for web programming, includingcryptography and support for standards like HTTP, JSON, and XML.

There is no clear criterion that defines what is included because fora long time, this was theonly Go library.There are criteria that define what gets added today, however.

New additions to the standard library are rare and the bar forinclusion is high.Code included in the standard library bears a large ongoing maintenance cost(often borne by those other than the original author),is subject to theGo 1 compatibility promise(blocking fixes to any flaws in the API),and is subject to the Gorelease schedule,preventing bug fixes from being available to users quickly.

Most new code should live outside of the standard library and be accessiblevia thego tool’sgo get command.Such code can have its own maintainers, release cycle,and compatibility guarantees.Users can find packages and read their documentation atpkg.go.dev.

Although there are pieces in the standard library that don’t really belong,such aslog/syslog, we continue to maintain everything in thelibrary because of the Go 1 compatibility promise.But we encourage most new code to live elsewhere.

Implementation

What compiler technology is used to build the compilers?

There are several production compilers for Go, and a number of othersin development for various platforms.

The default compiler,gc, is included with theGo distribution as part of the support for thegocommand.Gc was originally written in Cbecause of the difficulties of bootstrapping—you’d need a Go compiler toset up a Go environment.But things have advanced and since the Go 1.5 release the compiler has beena Go program.The compiler was converted from C to Go using automatic translation tools, asdescribed in thisdesign documentandtalk.Thus the compiler is now “self-hosting”, which means we needed to facethe bootstrapping problem.The solution is to have a working Go installation already in place,just as one normally has with a working C installation.The story of how to bring up a new Go environment from sourceis describedhere andhere.

Gc is written in Go with a recursive descent parserand uses a custom loader, also written in Go butbased on the Plan 9 loader, to generate ELF/Mach-O/PE binaries.

TheGccgo compiler is a front end written in C++with a recursive descent parser coupled to thestandard GCC back end. An experimentalLLVM back end isusing the same front end.

At the beginning of the project we considered using LLVM forgc but decided it was too large and slow to meetour performance goals.More important in retrospect, starting with LLVM would have made itharder to introduce some of the ABI and related changes, such asstack management, that Go requires but are not part of the standardC setup.

Go turned out to be a fine language in which to implement a Go compiler,although that was not its original goal.Not being self-hosting from the beginning allowed Go’s design toconcentrate on its original use case, which was networked servers.Had we decided Go should compile itself early on, we might haveended up with a language targeted more for compiler construction,which is a worthy goal but not the one we had initially.

Althoughgc has its own implementation, a native lexer andparser are available in thego/parser packageand there is also a nativetype checker.Thegc compiler uses variants of these libraries.

How is the run-time support implemented?

Again due to bootstrapping issues, the run-time code was originally written mostly in C (with atiny bit of assembler) but it has since been translated to Go(except for some assembler bits).Gccgo’s run-time support usesglibc.Thegccgo compiler implements goroutines usinga technique called segmented stacks,supported by recent modifications to the gold linker.Gollvm similarly is built on the correspondingLLVM infrastructure.

Why is my trivial program such a large binary?

The linker in thegc toolchaincreates statically-linked binaries by default.All Go binaries therefore include the Goruntime, along with the run-time type information necessary to support dynamictype checks, reflection, and even panic-time stack traces.

A simple C “hello, world” program compiled and linked statically usinggcc on Linux is around 750 kB, including an implementation ofprintf.An equivalent Go program usingfmt.Printf weighs a couple of megabytes, but that includesmore powerful run-time support and type and debugging information.

A Go program compiled withgc can be linked withthe-ldflags=-w flag to disable DWARF generation,removing debugging information from the binary but with noother loss of functionality.This can reduce the binary size substantially.

Can I stop these complaints about my unused variable/import?

The presence of an unused variable may indicate a bug, whileunused imports just slow down compilation,an effect that can become substantial as a program accumulatescode and programmers over time.For these reasons, Go refuses to compile programs with unusedvariables or imports,trading short-term convenience for long-term build speed andprogram clarity.

Still, when developing code, it’s common to create these situationstemporarily and it can be annoying to have to edit them out before theprogram will compile.

Some have asked for a compiler option to turn those checks offor at least reduce them to warnings.Such an option has not been added, though,because compiler options should not affect the semantics of thelanguage and because the Go compiler does not report warnings, onlyerrors that prevent compilation.

There are two reasons for having no warnings. First, if it’s worthcomplaining about, it’s worth fixing in the code. (Conversely, if it’s notworth fixing, it’s not worth mentioning.) Second, having the compilergenerate warnings encourages the implementation to warn about weakcases that can make compilation noisy, masking real errors thatshould be fixed.

It’s easy to address the situation, though. Use the blank identifierto let unused things persist while you’re developing.

import "unused"// This declaration marks the import as used by referencing an// item from the package.var _ = unused.Item  // TODO: Delete before committing!func main() {    debugData := debug.Profile()    _ = debugData // Used only during debugging.    ....}

Nowadays, most Go programmers use a tool,goimports,which automatically rewrites a Go source file to have the correct imports,eliminating the unused imports issue in practice.This program is easily connected to most editors and IDEs to run automatically when a Go source file is written.This functionality is also built intogopls, asdiscussed above.

Why does my virus-scanning software think my Go distribution or compiled binary is infected?

This is a common occurrence, especially on Windows machines, and is almost always a false positive.Commercial virus scanning programs are often confused by the structure of Go binaries, whichthey don’t see as often as those compiled from other languages.

If you’ve just installed the Go distribution and the system reports it is infected, that’s certainly a mistake.To be really thorough, you can verify the download by comparing the checksum with those on thedownloads page.

In any case, if you believe the report is in error, please report a bug to the supplier of your virus scanner.Maybe in time virus scanners can learn to understand Go programs.

Performance

Why does Go perform badly on benchmark X?

One of Go’s design goals is to approach the performance of C for comparableprograms, yet on some benchmarks it does quite poorly, including severalingolang.org/x/exp/shootout.The slowest depend on libraries for which versions of comparable performanceare not available in Go.For instance,pidigits.godepends on a multi-precision math package, and the Cversions, unlike Go’s, useGMP (which iswritten in optimized assembler).Benchmarks that depend on regular expressions(regex-dna.go,for instance) are essentially comparing Go’s nativeregexp package tomature, highly optimized regular expression libraries like PCRE.

Benchmark games are won by extensive tuning and the Go versions of mostof the benchmarks need attention. If you measure truly comparable Cand Go programs(reverse-complement.gois one example), you’ll see the two languages are much closer in raw performancethan this suite would indicate.

Still, there is room for improvement. The compilers are good but could bebetter, many libraries need major performance work, and the garbage collectorisn’t fast enough yet. (Even if it were, taking care not to generate unnecessarygarbage can have a huge effect.)

In any case, Go can often be very competitive.There has been significant improvement in the performance of many programsas the language and tools have developed.See the blog post aboutprofilingGo programs for an informative example.It’s quite old but still contains helpful information.

Changes from C

Why is the syntax so different from C?

Other than declaration syntax, the differences are not major and stemfrom two desires. First, the syntax should feel light, without toomany mandatory keywords, repetition, or arcana. Second, the languagehas been designed to be easy to analyzeand can be parsed without a symbol table. This makes it much easierto build tools such as debuggers, dependency analyzers, automateddocumentation extractors, IDE plug-ins, and so on. C and itsdescendants are notoriously difficult in this regard.

Why are declarations backwards?

They’re only backwards if you’re used to C. In C, the notion is that avariable is declared like an expression denoting its type, which is anice idea, but the type and expression grammars don’t mix very well andthe results can be confusing; consider function pointers. Go mostlyseparates expression and type syntax and that simplifies things (usingprefix* for pointers is an exception that proves the rule). In C,the declaration

    int* a, b;

declaresa to be a pointer but notb; in Go

    var a, b *int

declares both to be pointers. This is clearer and more regular.Also, the:= short declaration form argues that a full variabledeclaration should present the same order as:= so

    var a uint64 = 1

has the same effect as

    a := uint64(1)

Parsing is also simplified by having a distinct grammar for types thatis not just the expression grammar; keywords such asfuncandchan keep things clear.

See the article aboutGo’s Declaration Syntaxfor more details.

Why is there no pointer arithmetic?

Safety. Without pointer arithmetic it’s possible to create alanguage that can never derive an illegal address that succeedsincorrectly. Compiler and hardware technology have advanced to thepoint where a loop using array indices can be as efficient as a loopusing pointer arithmetic. Also, the lack of pointer arithmetic cansimplify the implementation of the garbage collector.

Why are++ and-- statements and not expressions? And why postfix, not prefix?

Without pointer arithmetic, the convenience value of pre- and postfixincrement operators drops. By removing them from the expressionhierarchy altogether, expression syntax is simplified and the messyissues around order of evaluation of++ and--(considerf(i++) andp[i] = q[++i])are eliminated as well. The simplification issignificant. As for postfix vs. prefix, either would work fine butthe postfix version is more traditional; insistence on prefix arosewith the STL, a library for a language whose name contains, ironically, apostfix increment.

Why are there braces but no semicolons? And why can’t I put the opening brace on the next line?

Go uses brace brackets for statement grouping, a syntax familiar toprogrammers who have worked with any language in the C family.Semicolons, however, are for parsers, not for people, and we wanted toeliminate them as much as possible. To achieve this goal, Go borrowsa trick from BCPL: the semicolons that separate statements are in theformal grammar but are injected automatically, without lookahead, bythe lexer at the end of any line that could be the end of a statement.This works very well in practice but has the effect that it forces abrace style. For instance, the opening brace of a function cannotappear on a line by itself.

Some have argued that the lexer should do lookahead to permit thebrace to live on the next line. We disagree. Since Go code is meantto be formatted automatically bygofmt,some style must be chosen. That style may differ from whatyou’ve used in C or Java, but Go is a different language andgofmt’s style is as good as any other. Moreimportant—much more important—the advantages of a single,programmatically mandated format for all Go programs greatly outweighany perceived disadvantages of the particular style.Note too that Go’s style means that an interactive implementation ofGo can use the standard syntax one line at a time without special rules.

Why do garbage collection? Won’t it be too expensive?

One of the biggest sources of bookkeeping in systems programs ismanaging the lifetimes of allocated objects.In languages such as C in which it is done manually,it can consume a significant amount of programmer time and isoften the cause of pernicious bugs.Even in languages like C++ or Rust that provide mechanismsto assist, those mechanisms can have a significant effect on thedesign of the software, often adding programming overheadof its own.We felt it was critical to eliminate suchprogrammer overheads, and advances in garbage collectiontechnology in the last few years gave us confidence that itcould be implemented cheaply enough, and with low enoughlatency, that it could be a viable approach for networkedsystems.

Much of the difficulty of concurrent programminghas its roots in the object lifetime problem:as objects get passed among threads it becomes cumbersometo guarantee they become freed safely.Automatic garbage collection makes concurrent code far easier to write.Of course, implementing garbage collection in a concurrent environment isitself a challenge, but meeting it once rather than in everyprogram helps everyone.

Finally, concurrency aside, garbage collection makes interfacessimpler because they don’t need to specify how memory is managed across them.

This is not to say that the recent work in languageslike Rust that bring new ideas to the problem of managingresources is misguided; we encourage this work and are excited to seehow it evolves.But Go takes a more traditional approach by addressingobject lifetimes throughgarbage collection, and garbage collection alone.

The current implementation is a mark-and-sweep collector.If the machine is a multiprocessor, the collector runs on a separate CPUcore in parallel with the main program.Major work on the collector in recent years has reduced pause timesoften to the sub-millisecond range, even for large heaps,all but eliminating one of the major objections to garbage collectionin networked servers.Work continues to refine the algorithm, reduce overhead andlatency further, and to explore new approaches.The 2018ISMM keynoteby Rick Hudson of the Go teamdescribes the progress so far and suggests some future approaches.

On the topic of performance, keep in mind that Go gives the programmerconsiderable control over memory layout and allocation, much more thanis typical in garbage-collected languages. A careful programmer can reducethe garbage collection overhead dramatically by using the language well;see the article aboutprofiling Go programs for a worked example,including a demonstration of Go’s profiling tools.

Release Notes

Learn about what's new in each Go release.

View release notes

Code of Conduct

Guidelines for participating in Go community spaces and reporting process for handing issues.

View more

Brand Guidelines

Guidance about reusing the Go logo, gopher mascot, etc.

View guidelines

Contribute Guide

Learn how to file bugs, pull requests, or otherwise contribute to the Go ecosystem.

View guide

Get connected

go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp