Go interview questions
110 questions, 91 with answers. 859 open jobs in India ask for Go.
Does Go have a runtime?
Go has an extensive runtime library, often just called the runtime, 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 analogous to
libc, the C library.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 "runtime" is just the name given to the library providing critical language services.
From Go Frequently Asked Questions (CC BY 4.0)
What's up with Unicode identifiers?
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—identifier characters must be letters or digits as defined by Unicode—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.
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
X日本語, which is clearly unsatisfactory.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 recommendations 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.
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.
From Go Frequently Asked Questions (CC BY 4.0)
Why does Go not have feature X?
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.
If it bothers you that Go is missing feature X, please forgive us and investigate the features that Go does have. You might find that they compensate in interesting ways for the lack of X.
From Go Frequently Asked Questions (CC BY 4.0)
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 the language spec and the proposal for details.
From Go Frequently Asked Questions (CC BY 4.0)
Why was Go initially released without generic types?
Go was intended as a language for writing server programs that would be easy to maintain over time. (See this article 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 initially left out for simplicity.
Generics are convenient but they come at a cost in complexity in the type system and run-time. It took a while to develop a design that we believe gives value proportionate to the complexity.
From Go Frequently Asked Questions (CC BY 4.0)
Why does Go not have exceptions?
We believe that coupling exceptions to a control structure, as in the
try-catch-finallyidiom, 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.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 canonical error type, coupled with Go's other features, makes error handling pleasant but quite different from that in other languages.
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.
See the Defer, Panic, and Recover article for details. Also, the Errors are values 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 be deployed in error handling.
From Go Frequently Asked Questions (CC BY 4.0)
Why does Go not have assertions?
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.
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.
From Go Frequently Asked Questions (CC BY 4.0)
Why build concurrency on the ideas of CSP?
Concurrency and multi-threaded programming have over time developed a reputation for difficulty. We believe this is due partly to complex designs such as pthreads 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.
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.
From Go Frequently Asked Questions (CC BY 4.0)
Why goroutines instead of threads?
Goroutines are part of making concurrency easy to use. The idea, which has been around for a while, is to multiplex independently executing functions—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 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.
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.
From Go Frequently Asked Questions (CC BY 4.0)
Why are map operations not defined to be atomic?
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.
The language does not preclude atomic map updates. When required, such as when hosting an untrusted program, the implementation could interlock map 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 a
forrangeloop—and not changing the map by 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 language contain a special check that automatically reports at run time when a map is modified unsafely by concurrent execution. Also there is a type in the sync library called
sync.Mapthat works well for certain usage patterns such as static caches, although it is not suitable as a general replacement for the builtin map type.From Go Frequently Asked Questions (CC BY 4.0)
Will you accept my language change?
People often suggest improvements to the language—the mailing list contains a rich history of such discussions—but very few of these changes have been accepted.
Although Go is an open source project, the language and libraries are protected by a compatibility promise 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.
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 Go at Google: Language Design in the Service of Software Engineering explains Go's origins and the motivation behind its design.
From Go Frequently Asked Questions (CC BY 4.0)
Is Go an object-oriented language?
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 "interface" 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—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 such as plain, "unboxed" integers. They are not restricted to structs (classes).
Also, the lack of a type hierarchy makes "objects" in Go feel much more lightweight than in languages such as C++ or Java.
From Go Frequently Asked Questions (CC BY 4.0)
How do I get dynamic dispatch of methods?
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.
From Go Frequently Asked Questions (CC BY 4.0)
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 a different approach.
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—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—without annotating the original types. Because there are no explicit relationships between types and interfaces, there is no type hierarchy to manage or discuss.
It's possible to use these ideas to construct something analogous to type-safe Unix pipes. For instance, see how
fmt.Fprintfenables formatted printing to any output, not just a file, or how thebufiopackage can be completely separate from file I/O, or how theimagepackages generate compressed image 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 type dependency is one of the most productive things about Go.
From Go Frequently Asked Questions (CC BY 4.0)
Why is
lena function and not a method?We debated this issue but decided implementing
lenand friends as functions was fine in practice and didn't complicate questions about the interface (in the Go type sense) of basic types.From Go Frequently Asked Questions (CC BY 4.0)
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 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.
Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.
From Go Frequently Asked Questions (CC BY 4.0)
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 without needing to modify existing code. It enables a kind of structural typing 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.
See the question on type inheritance for more detail.
From Go Frequently Asked Questions (CC BY 4.0)
How can I guarantee my type satisfies an interface?
You can ask the compiler to check that the type
Timplements the interfaceIby attempting an assignment using the zero value forTor pointer toT, as appropriate:type T struct{} var _ I = T{} // Verify that T implements I. var _ I = (*T)(nil) // Verify that *T implements I.If
T(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 implement it, 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 the
ImplementsFooermethod to be aFooer, clearly documenting the fact and announcing it in go 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 of the interface idea. Sometimes, though, they're necessary to resolve ambiguities among similar interfaces.
From Go Frequently Asked Questions (CC BY 4.0)
Why doesn't type T satisfy the Equal interface?
Consider this simple interface to represent an object that can compare itself with another value:
type Equaler interface { Equal(Equaler) bool }and this type,
T:type T int func (t T) Equal(u T) bool { return t == u } // does not satisfy EqualerUnlike the analogous situation in some polymorphic type systems,
Tdoes not implementEqualer. The argument type ofT.EqualisT, not literally the required typeEqualer.In Go, the type system does not promote the argument of
Equal; that is the programmer's responsibility, as illustrated by the typeT2, which does implementEqualer:type T2 int func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies EqualerEven this isn't like other type systems, though, because in Go any type that satisfies
Equalercould be passed as the argument toT2.Equal, and at run time we must check 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.FileIn Go,
T3does not satisfyOpener, although it might in another language.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.
From Go Frequently Asked Questions (CC BY 4.0)
Can I convert a []T to an []interface{}?
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
intto a slice ofinterface{}:t := []int{1, 2, 3, 4} s := make([]interface{}, len(t)) for i, v := range t { s[i] = v }From Go Frequently Asked Questions (CC BY 4.0)
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 int type T2 int var t1 T1 var x = T2(t1) // OK var st1 []T1 var sx = ([]T2)(st1) // NOT OKIn 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.
From Go Frequently Asked Questions (CC BY 4.0)
Why is my nil error value not equal to nil?
Under the covers, interfaces are implemented as two elements, a type
Tand a valueV.Vis a concrete value such as anint,structor pointer, never an interface itself, and has typeT. For instance, if we store theintvalue 3 in an interface, the resulting interface value has, schematically, (T=int,V=3). The valueVis also known as the interface's dynamic value, since a given interface variable might hold different valuesV(and corresponding typesT) during the execution of the program.An interface value is
nilonly if theVandTare both unset, (T=nil,Vis not set), In particular, anilinterface will always hold aniltype. If we store anilpointer of type*intinside an interface value, the inner type will be*intregardless of the value of the pointer: (T=*int,V=nil). Such an interface value will therefore be non-nileven when the pointer valueVinside isnil.This situation can be confusing, and arises when a
nilvalue is stored inside an interface value such as anerrorreturn: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 a
nilp, so the return value is anerrorinterface value 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 propernilerrorto the caller, the function must return an explicitnil:func returnsError() error { if bad() { return ErrBad } return nil }It's a good idea for functions that return errors always to use the
errortype in their signature (as we did above) rather than a concrete type such as*MyError, to help guarantee the error is created correctly. As an example,os.Openreturns anerroreven 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 value has been stored in the interface, the interface will not be
nil. For more information, see The Laws of Reflection.From Go Frequently Asked Questions (CC BY 4.0)
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 types are 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 same location in memory. This is safe as no value can be stored in those variables.
Moreover, the language does not make any guarantees as to whether pointers to two different zero-size variables will compare equal or not. Such comparisons may even return
trueat one point in the program and then returnfalseat a different point, depending on exactly how the program is compiled and executed.A separate issue with zero-size types is that a pointer to a zero-size struct field must not overlap with a pointer to a different object in memory. That could cause confusion in the garbage collector. This means that if the last field in a struct is zero-size, the struct will be padded to ensure that a pointer to the last field does not overlap 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 print
2, not1, in most Go implementations.From Go Frequently Asked Questions (CC BY 4.0)
Why are there no untagged unions, as in C?
Untagged unions would violate Go's memory safety guarantees.
From Go Frequently Asked Questions (CC BY 4.0)
Why does Go not have variant types?
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.
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?
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.
From Go Frequently Asked Questions (CC BY 4.0)
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() Valuebecause
Valueimplements the empty interface. In Go method types must match exactly, soValuedoes not implementCopyable. Go separates the notion of what a type 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 to express a type hierarchy through interfaces. In Go it's more natural to have a clean separation between interface and implementation.From Go Frequently Asked Questions (CC BY 4.0)
Why does Go not provide implicit numeric conversions?
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; 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 straightforward at the cost of some explicit conversions in the code. The definition of constants in Go—arbitrary precision values free of signedness and size annotations—ameliorates matters considerably, though.
A related detail is that, unlike in C,
intandint64are distinct types even ifintis a 64-bit type. Theinttype is generic; if you care about how many bits an integer holds, Go encourages you to be explicit.From Go Frequently Asked Questions (CC BY 4.0)
How do constants work in Go?
Although Go is strict about conversion between variables of different numeric types, constants in the language are much more flexible. Literal constants such as
23,3.14159andmath.Pioccupy a sort of ideal number space, with arbitrary precision and no overflow or underflow. For instance, the value ofmath.Piis specified to 63 decimal digits in the source code, and constant expressions involving the value keep precision beyond what afloat64could hold. Only when the constant or constant expression is assigned to a variable—a memory location in the program—does it become a "computer" number with the usual floating-point properties and precision.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
sqrt2 := math.Sqrt(2)without complaint from the compiler because the ideal number
2can be converted safely and accurately to afloat64for the call tomath.Sqrt.A blog post titled Constants explores this topic in more detail.
From Go Frequently Asked Questions (CC BY 4.0)
Why are maps built in?
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.
From Go Frequently Asked Questions (CC BY 4.0)
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 slices will not invalidate any existing programs—but without a clear idea of what equality 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.
From Go Frequently Asked Questions (CC BY 4.0)
After the last page: 19 questions more, without answers. Go to the last page
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Go Frequently Asked Questionsby the Go AuthorsCC BY 4.073 questions
- Tech Vaultby moabukar and contributorsApache 2.019 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA18 questions