Golang / GoLang Basics Interview Questions
1. What is Go and why was it created at Google?
Go (also called Golang) is an open-source, statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It was announced in 2009 and reached version 1.0 in 2012. The creators were frustrated with the tools available at Google. C++ compile tim...
2. What are the key characteristics that make Go different from other popular languages?
Go has a deliberately small feature set. Every design decision was made by asking: does this add enough value to justify the complexity it introduces? The result is a language that experienced developers can learn in days and that reads consistently across large teams. Go Key Characteristics Char...
3. What are packages in Go and what is special about the 'main' package?
Every Go source file starts with a package declaration. Packages are Go's unit of code organisation, encapsulation, and compilation. A package groups related types, functions, constants, and variables. The main package is unique: it defines an executable program. The main() function within it is ...
4. What are the different ways to declare variables in Go?
Go offers several declaration styles. The choice between them is mostly about context (package level vs inside a function) and verbosity. Every variable is always initialised — Go has no uninitialized variables. Variable Declaration Styles Style Where usable Type required? Notes var name type Any...
5. What are the fundamental data types in Go?
Go has a concise but complete set of built-in primitive types. Choosing the right type — especially between int and sized integers, and between float32 and float64 — matters for correctness and interoperability. Go Primitive Types Category Types Common default Signed integers int8, int16, int32, ...
6. How do constants and iota work in Go?
Constants are declared with const and must be assigned a value that is computable at compile time — no function calls or runtime values. The iota identifier provides an automatically incrementing integer within a const block, resetting to 0 at the start of each new block. // Simple constants cons...
7. How are functions defined in Go? What are variadic functions and named return values?
Functions are first-class citizens in Go — they can be assigned to variables, passed as arguments, and returned from other functions. Go functions support multiple return values (the primary mechanism for error handling), named returns, and variadic parameters. // Basic function with multiple ret...
8. How do if, for, and switch statements work in Go?
Go has a deliberately minimal set of control-flow constructs. There is only one loop keyword — for — which covers everything a while , do-while , and classic for loop does in other languages. // if with an init statement â err is only in scope inside the if block if err := doWork(); err != nil ...
9. What is the difference between arrays and slices in Go?
Arrays and slices are both ordered sequences, but they work very differently. Arrays are value types with a fixed size baked into their type; slices are reference types that provide a flexible view into an underlying array. Array vs Slice Aspect Array Slice Size Fixed at compile time; part of the...
10. How do maps work in Go? What are the key operations and pitfalls?
Maps are Go's built-in hash table. Keys must be comparable types (those that support == and != ). Maps are reference types — like slices, they are cheap to pass because only a header is copied. // Creating maps m := map[string]int{} // empty map literal (ready to use) m2 := make(map[string]int) /...
11. How do structs work in Go and how do you attach methods to them?
Structs are Go's primary mechanism for grouping related data. Methods are functions with a receiver — the type they are attached to. The receiver can be a value or a pointer, which changes whether the method can modify the struct. type Person struct { FirstName string LastName string Age int emai...
12. How do interfaces work in Go? How do you use type assertions and type switches?
An interface specifies a set of method signatures. Any type that implements all the methods satisfies the interface — implicitly, with no declaration. This is sometimes called structural typing or duck typing with static checking . // Interface definition type Shape interface { Area() float64 Per...
13. What is the empty interface (any / interface{}) and when should you use it?
An interface with zero methods is satisfied by every type in Go. Written as interface{} or its alias any (Go 1.18+), it lets a variable or function parameter hold a value of any type. It is Go's mechanism for truly generic containers — at the cost of compile-time type safety. // any is an alias f...
14. How do pointers work in Go and how are they safer than C pointers?
Go has pointers — variables that store the memory address of another variable — but removes the dangerous parts of C pointers. There is no pointer arithmetic, no manual memory management, and the garbage collector handles deallocation. A pointer to a local variable is safe to return from a functi...
15. How does Go handle errors, and what is the difference between %v and %w in fmt.Errorf?
Go treats errors as values returned by functions, not as exceptions thrown from the call stack. This makes error handling explicit and visible. Every function that can fail returns an error as its last return value. The caller is responsible for handling it. // error is a built-in interface: type...
16. What are goroutines and how do you use sync.WaitGroup to wait for them?
A goroutine is a lightweight, concurrently executing function managed by the Go runtime. The cost to create one is ~2 KB of stack and ~300 ns — roughly 1000× cheaper than an OS thread. The runtime multiplexes goroutines onto OS threads with its own scheduler. // Launch a goroutine with the 'go' k...
17. What are channels in Go and what is the difference between buffered and unbuffered?
Channels are typed conduits for sending values between goroutines. They are goroutine-safe and provide the synchronisation primitive underlying Go's concurrency model. Go's philosophy: "Do not communicate by sharing memory; instead, share memory by communicating." // Unbuffered channel â send B...
18. How do defer, panic, and recover work together in Go?
defer schedules a function call to run when the surrounding function returns — regardless of how it returns (normally, via error, or via panic). It is Go's idiomatic resource-cleanup mechanism. panic stops normal execution; recover catches it inside a deferred function. // defer â executes when...
19. What are closures in Go and what is the loop variable capture gotcha?
A closure is a function that references and closes over variables from its surrounding scope. The closure captures the variable itself — not a copy of its value at the moment of creation. This distinction is the source of one of the most common Go bugs. // Closure capturing outer variable func ma...
20. What is the init() function and when does it run?
init() is an optional special function that runs automatically after all package-level variable initialisations — before main() . It takes no arguments, returns nothing, and cannot be called directly. A single file may contain multiple init() functions. package main import ( "fmt" _ "github.com/l...
21. What is the Go module system? What do go.mod and go.sum contain?
Modules are Go's dependency management system (stable since Go 1.13). A module is a collection of related packages identified by a module path (typically a repository URL). The module's root contains a go.mod file that records the module path, the minimum Go version, and all required dependencies...
22. What is a data race in Go and how do you detect one?
A data race occurs when two or more goroutines access the same memory location concurrently, at least one access is a write, and there is no synchronisation between them. Data races produce undefined, non-deterministic behaviour — results vary between runs and can silently corrupt data. // DATA R...
23. What is the fmt.Stringer interface and how does it control how a type is printed?
The fmt package defines the Stringer interface: a type that implements String() string controls how it appears when printed with fmt.Println , fmt.Printf("%v") , and related functions. Implementing error works the same way for error messages. // fmt.Stringer interface: // type Stringer interface ...
24. What is the difference between a type definition and a type alias in Go?
Go has two ways to give a new name to a type, with importantly different semantics. Understanding this prevents subtle type-safety bugs and confusing compiler errors. Type Definition vs Type Alias Aspect Type Definition: type T U Type Alias: type T = U Creates new type? YES — T and U are distinct...
25. How does Go handle strings, runes, and bytes? Why is len(s) not the character count?
Go strings are immutable sequences of bytes stored in UTF-8 encoding. Since UTF-8 is a variable-width encoding, a single character (rune) can occupy 1 to 4 bytes. This means len(s) reports bytes , not characters — a fact that trips up many beginners. s := "Hello, ä¸ç" // UTF-8 string containin...
26. What is a goroutine leak and what is the idiomatic way to prevent one?
A goroutine leak occurs when a goroutine is started but never terminates — it stays blocked forever waiting on a channel, mutex, or network call that will never complete. Goroutines are cheap but not free: leaked goroutines accumulate over time and eventually exhaust memory in long-running servic...
27. What is sync.Mutex and when do you use sync.RWMutex instead?
sync.Mutex provides mutual exclusion — at most one goroutine holds the lock at any moment. sync.RWMutex is an extension: multiple goroutines can hold a read lock simultaneously, but a write lock is exclusive. Use RWMutex when reads vastly outnumber writes. // sync.Mutex â protect any shared mut...
28. How does struct embedding promote methods in Go, and how does it differ from inheritance?
Go uses composition through embedding rather than class inheritance. When a type is embedded (without a field name), its exported methods and fields are promoted to the outer type — they are directly accessible. However, the outer type is NOT a subtype of the embedded type. type Logger struct { p...
29. How does append() work internally in Go? When does it allocate new memory?
append adds elements to a slice. When there is spare capacity in the backing array, it writes directly into it and increments the length — no allocation. When capacity is exhausted, it allocates a new, larger array, copies all elements, and returns a new slice header. This is why you must always ...
30. What is context.Context and why is it the first parameter in so many Go functions?
context.Context is Go's standard mechanism for propagating three things across API boundaries and goroutine calls: cancellation signals , deadlines , and request-scoped values . Passing it as the first parameter is a Go convention — it allows any blocking call to be cancelled. // The context.Cont...
31. What is the 'typed nil' trap in Go and why does 'if err != nil' sometimes fail?
An interface value in Go has two components: a dynamic type and a dynamic value. An interface is nil only when BOTH are nil. A common mistake is returning a typed nil pointer as an error — the interface has a type component set, so it is NOT nil even though the pointer value is nil. // The trap: ...
32. What are the most important formatting verbs in Go's fmt package?
Knowing fmt format verbs lets you produce clear output for debugging, logging, and user messages. The %v verb is the universal default; specialised verbs give more control. Key fmt Format Verbs Verb Meaning Example output %v Default format for any value 42, true, [1 2 3] %+v Struct with field nam...