{"id":947,"date":"2026-10-11T10:00:00","date_gmt":"2026-10-11T04:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/"},"modified":"2026-11-29T01:29:23","modified_gmt":"2026-11-28T19:59:23","slug":"go-interview-questions","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/","title":{"rendered":"Go Interview Questions: 150 Most Asked, with Full Answers"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go interview questions are now common in backend, cloud and DevOps hiring, because many teams build their APIs, tools and microservices in Go. This post gives you the 150 most asked questions, grouped from basic to advanced, and every single one now has a full answer in simple English, with code examples you can run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This page is the complete, all-in-one list. For around 100 questions on each single topic, use the 29 topic posts in our <a href=\"https:\/\/smitabharat.com\/blog\/go-interview-questions-hub\/\">Go topic-wise interview hub<\/a>. For coding rounds, practise the <a href=\"https:\/\/smitabharat.com\/blog\/go-coding-interview-programs\/\">Go coding interview programs<\/a>, and for a full study plan, see <a href=\"https:\/\/smitabharat.com\/blog\/all-interview-questions\/\">all interview questions with a study path<\/a>. All answers match current Go releases.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Do Go Interview Questions Cover?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go (also called Golang) is a simple, fast, compiled language made at Google. Also, it has built-in concurrency with goroutines and channels, a strong standard library, and quick build times.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of Go as a well-organised kitchen. There are only a few tools, but each one is sharp and easy to find. Interviewers check that you know each tool, and that you know when to use which one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most Go interview questions test six areas: basics and types, functions and methods, interfaces and errors, concurrency, the standard library and tooling, and real backend design. Senior rounds add performance, memory and architecture.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Use These Go Interview Questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Do not try to memorise 150 answers in one go. Instead, use the list in three passes.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, read each question and try to answer it in two or three sentences before you read the answer.<\/li>\n\n\n<li>Next, run the code examples yourself and change them a little, because running code makes answers stick.<\/li>\n\n\n<li>Finally, mark the questions you missed and practise them out loud a few days later.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Every full program in this post was run, and its exact output is shown below it. Short snippets that need a server, a database, a test file or a newer Go version are marked as examples only. The table below shows how interview rounds usually use these questions.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Round<\/th><th>Focus<\/th><th>Questions<\/th><\/tr><\/thead><tbody><tr><td>Phone screen<\/td><td>Basics, types, slices, maps<\/td><td>Q1 to Q45<\/td><\/tr><tr><td>Technical round<\/td><td>Interfaces, errors, concurrency<\/td><td>Q46 to Q105<\/td><\/tr><tr><td>Senior round<\/td><td>Tooling, performance, design<\/td><td>Q106 to Q143<\/td><\/tr><tr><td>Scenario round<\/td><td>Real production problems<\/td><td>Q144 to Q150<\/td><\/tr><tr><td>Live coding<\/td><td>Write and explain a program<\/td><td>Hands-on section<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Code Runs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before the questions, it helps to see how a Go program goes from source code to a running service. Interviewers often ask about this flow.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-1024x640.png\" alt=\"Go interview questions diagram showing source code, go build, a single binary and the Go runtime with goroutines\" class=\"wp-image-945\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">go build turns your code into one static binary, and the Go runtime inside it schedules goroutines and manages memory.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">First, the go build command compiles your packages into one binary file. Then that binary includes the Go runtime, which runs your goroutines on a few operating system threads and cleans up memory with its garbage collector. So you can copy one file to a server and run it, with no extra installs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go interview questions check that you know the core language. Freshers should be able to answer all of them, so read each answer slowly and run the small examples.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is Go, and why did Google create it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go (also called Golang) is an open-source programming language made at Google by Robert Griesemer, Rob Pike and Ken Thompson. It was announced in 2009, and version 1.0 came out in 2012.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Google built Go because its big C++ and Java projects were slow to compile and hard to manage. So the team wanted a language that is simple to read, compiles in seconds, and handles many tasks at the same time. Today Go powers tools like Docker, Kubernetes and Terraform, and many backend APIs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What are the main features of Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go keeps a small set of features, but each one is useful. Here are the ones interviewers expect you to name.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Simple syntax:<\/strong> only 25 keywords, so code is easy to read.<\/li>\n\n\n<li><strong>Fast compilation:<\/strong> large projects build in seconds.<\/li>\n\n\n<li><strong>Static typing:<\/strong> the compiler catches type mistakes before the program runs.<\/li>\n\n\n<li><strong>Built-in concurrency:<\/strong> goroutines and channels make it easy to run work at the same time.<\/li>\n\n\n<li><strong>Garbage collection:<\/strong> Go frees unused memory for you.<\/li>\n\n\n<li><strong>Strong standard library:<\/strong> HTTP, JSON, testing, crypto and more are built in.<\/li>\n\n\n<li><strong>Single binary:<\/strong> your program and the runtime become one file that is easy to deploy.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. Is Go compiled or interpreted?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go is a compiled language. The <code>go build<\/code> command turns your source code into native machine code for your operating system and CPU. So there is no interpreter or virtual machine at run time, unlike Python or Java.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Even <code>go run main.go<\/code> compiles first. It just builds the program in a temporary folder and runs it straight away.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. Is Go an object-oriented language?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Go FAQ answers &#8220;yes and no&#8221;. Go has types and methods, so you can write in an object-oriented style. However, it has no classes and no inheritance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead, Go uses three simple tools. Structs hold data, methods attach behaviour to a type, and interfaces describe what a type can do. You build bigger types by embedding smaller ones, which is called composition.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. What is a package, and what is package main?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A package is a folder of <code>.go<\/code> files that belong together, such as <code>fmt<\/code>, <code>strings<\/code> or your own <code>orders<\/code> package. Every Go file starts with a <code>package<\/code> line. Packages help you organise code and reuse it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>package main<\/code> is special. It tells Go to build an executable program instead of a library. A <code>main<\/code> package must have a <code>func main()<\/code>, which is where the program starts.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(\"Hello from package main\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Hello from package main<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What is the difference between var and := ?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both create variables, but they work in slightly different places.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>var<\/th><th>:=<\/th><\/tr><\/thead><tbody><tr><td>Where it works<\/td><td>Inside and outside functions<\/td><td>Only inside functions<\/td><\/tr><tr><td>Type<\/td><td>Can be written or guessed<\/td><td>Always guessed from the value<\/td><\/tr><tr><td>Start value<\/td><td>Optional<\/td><td>Required<\/td><\/tr><tr><td>Example<\/td><td><code>var age int = 30<\/code><\/td><td><code>age := 30<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So use <code>:=<\/code> for most local variables, because it is short. Use <code>var<\/code> for package-level variables, or when you want the zero value, such as <code>var total int<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. What are zero values in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, every variable always has a value. If you do not give one, Go sets a default called the zero value. This means you never read random garbage memory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    var count int\n    var price float64\n    var name string\n    var active bool\n    var scores []int\n    var ages map[string]int\n\n    fmt.Println(count, price, active)\n    fmt.Printf(\"name=%q\\n\", name)\n    fmt.Println(scores == nil, ages == nil)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 0 false\nname=\"\"\ntrue true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So numbers start at <code>0<\/code>, strings at <code>\"\"<\/code>, booleans at <code>false<\/code>, and pointers, slices, maps, channels, functions and interfaces at <code>nil<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. What are the basic data types in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has a small set of built-in types. The table below groups them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Group<\/th><th>Types<\/th><\/tr><\/thead><tbody><tr><td>Boolean<\/td><td><code>bool<\/code><\/td><\/tr><tr><td>Signed integers<\/td><td><code>int<\/code>, <code>int8<\/code>, <code>int16<\/code>, <code>int32<\/code>, <code>int64<\/code><\/td><\/tr><tr><td>Unsigned integers<\/td><td><code>uint<\/code>, <code>uint8<\/code>, <code>uint16<\/code>, <code>uint32<\/code>, <code>uint64<\/code>, <code>uintptr<\/code><\/td><\/tr><tr><td>Floating point<\/td><td><code>float32<\/code>, <code>float64<\/code><\/td><\/tr><tr><td>Complex<\/td><td><code>complex64<\/code>, <code>complex128<\/code><\/td><\/tr><tr><td>Text<\/td><td><code>string<\/code>, <code>byte<\/code> (same as <code>uint8<\/code>), <code>rune<\/code> (same as <code>int32<\/code>)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">On top of these, Go has composite types: arrays, slices, maps, structs, pointers, functions, interfaces and channels.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. What is the difference between int, int32 and int64?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>int32<\/code> is always 32 bits and <code>int64<\/code> is always 64 bits, on every machine. <code>int<\/code> depends on the platform. It is 64 bits on 64-bit systems, which is almost every server today, and 32 bits on 32-bit systems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>int<\/code> for counters, lengths and indexes, because built-ins like <code>len<\/code> return <code>int<\/code>. Use a fixed size such as <code>int64<\/code> when the size matters, for example in file formats, network protocols or database columns. Also, Go never mixes them silently, so <code>int<\/code> plus <code>int64<\/code> needs a conversion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. What is a rune, and how is it different from a byte?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>byte<\/code> is an alias for <code>uint8<\/code> and holds one raw byte. A <code>rune<\/code> is an alias for <code>int32<\/code> and holds one Unicode character (a code point). Go strings are stored as UTF-8 bytes, and many characters, like Hindi letters or emojis, take more than one byte.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    word := \"h\u00e9llo\"\n    fmt.Println(\"bytes:\", len(word))         \/\/ \u00e9 takes 2 bytes\n    fmt.Println(\"runes:\", len([]rune(word))) \/\/ 5 characters\n    fmt.Println(word[1], string([]rune(word)[1]))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>bytes: 6\nrunes: 5\n195 \u00e9<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So <code>word[1]<\/code> gives a single byte (195), while converting to <code>[]rune<\/code> gives you whole characters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. What is a constant, and what does iota do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A constant is a value fixed at compile time that never changes, such as <code>const maxUsers = 100<\/code>. Constants can be numbers, strings or booleans.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>iota<\/code> is a counter used inside a <code>const<\/code> block. It starts at 0 and goes up by one on each line. So it is handy for building enums.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Weekday int\n\nconst (\n    Sunday  Weekday = iota \/\/ 0\n    Monday                 \/\/ 1\n    Tuesday                \/\/ 2\n)\n\nconst (\n    _  = iota             \/\/ skip 0\n    KB = 1 &lt;&lt; (10 * iota) \/\/ 1 &lt;&lt; 10\n    MB                    \/\/ 1 &lt;&lt; 20\n)\n\nfunc main() {\n    fmt.Println(Sunday, Monday, Tuesday)\n    fmt.Println(KB, MB)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 1 2\n1024 1048576<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. Does Go have implicit type conversion?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Go never converts between types for you, even between <code>int<\/code> and <code>int64<\/code> or <code>int<\/code> and <code>float64<\/code>. You must convert on purpose, for example <code>float64(count)<\/code>. This stops many hidden bugs, such as losing decimals without noticing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The only exception is untyped constants. For example, <code>var x float64 = 3<\/code> works, because the constant <code>3<\/code> has no fixed type until it is used.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q13. How do you convert a string to an int and back?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use the <code>strconv<\/code> package. <code>strconv.Atoi<\/code> turns a string into an <code>int<\/code> and returns an error if the text is not a number. <code>strconv.Itoa<\/code> turns an <code>int<\/code> into a string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    age, err := strconv.Atoi(\"42\")\n    fmt.Println(age+1, err)\n\n    _, err = strconv.Atoi(\"forty\")\n    fmt.Println(err)\n\n    text := strconv.Itoa(2026)\n    fmt.Println(text + \"!\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>43 &lt;nil&gt;\nstrconv.Atoi: parsing \"forty\": invalid syntax\n2026!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use <code>string(65)<\/code> to turn a number into text. It gives the character with that code, &#8220;A&#8221;, not &#8220;65&#8221;, and <code>go vet<\/code> warns about it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q14. What loops does Go have?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has only one loop keyword, <code>for<\/code>, but it covers every kind of loop. There is no <code>while<\/code> or <code>do while<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 0; i &lt; 3; i++ { \/\/ classic three-part loop\n        fmt.Print(i, \" \")\n    }\n    fmt.Println()\n\n    n := 1\n    for n &lt; 20 { \/\/ works like a while loop\n        n *= 3\n    }\n    fmt.Println(n)\n\n    for index, fruit := range []string{\"apple\", \"mango\"} { \/\/ range loop\n        fmt.Println(index, fruit)\n    }\n\n    for i := range 3 { \/\/ range over an integer, Go 1.22+\n        fmt.Print(i, \" \")\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 1 2\n27\n0 apple\n1 mango\n0 1 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A plain <code>for { }<\/code> with no condition runs forever until you <code>break<\/code> or <code>return<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q15. How does a switch statement work in Go, and does it fall through?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A Go <code>switch<\/code> runs the first matching case and then stops. It does not fall through to the next case, so you do not need <code>break<\/code>. If you really want to continue into the next case, you write <code>fallthrough<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc grade(marks int) string {\n    switch { \/\/ a switch with no value works like an if-else chain\n    case marks &gt;= 90:\n        return \"A\"\n    case marks &gt;= 75:\n        return \"B\"\n    default:\n        return \"C\"\n    }\n}\n\nfunc main() {\n    fmt.Println(grade(95), grade(80), grade(40))\n\n    switch day := \"sat\"; day {\n    case \"sat\", \"sun\": \/\/ one case can match many values\n        fmt.Println(\"weekend\")\n    default:\n        fmt.Println(\"weekday\")\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>A B C\nweekend<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q16. What does the blank identifier _ do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The blank identifier <code>_<\/code> is a placeholder for a value you want to ignore. Go does not allow unused variables, so <code>_<\/code> lets you skip what you do not need.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are common uses.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Skip a return value: <code>_, err := strconv.Atoi(s)<\/code>.<\/li>\n\n\n<li>Skip the index in a loop: <code>for _, v := range items<\/code>.<\/li>\n\n\n<li>Import a package only for its side effects: <code>import _ \"github.com\/lib\/pq\"<\/code>.<\/li>\n\n\n<li>Check at compile time that a type meets an interface: <code>var _ io.Reader = (*MyReader)(nil)<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q17. How do exported and unexported names work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go uses the first letter of a name to control visibility. If a name starts with a capital letter, such as <code>Total<\/code> or <code>NewServer<\/code>, it is exported and other packages can use it. If it starts with a small letter, such as <code>total<\/code>, it is unexported and stays private to its own package.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This rule applies to functions, types, variables, constants, struct fields and methods. So there is no <code>public<\/code> or <code>private<\/code> keyword in Go. Also, <code>encoding\/json<\/code> can only see exported struct fields.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q18. What does the init function do, and when does it run?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>init<\/code> is a special function that Go calls automatically before <code>main<\/code>. It takes no arguments and returns nothing, and you never call it yourself. A package can have several <code>init<\/code> functions, even in one file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The order is simple. First, imported packages are set up. Then the package-level variables are set, then every <code>init<\/code> runs, and finally <code>main<\/code> starts.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nvar appName = setName()\n\nfunc setName() string {\n    fmt.Println(\"1. package variable set\")\n    return \"shop\"\n}\n\nfunc init() {\n    fmt.Println(\"2. init runs\")\n}\n\nfunc main() {\n    fmt.Println(\"3. main runs for\", appName)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1. package variable set\n2. init runs\n3. main runs for shop<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Keep <code>init<\/code> small. Heavy work like database connections is better in <code>main<\/code>, where you can handle errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q19. What is a Go module, and what are go.mod and go.sum?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A module is a collection of Go packages that are versioned together, usually one Git repository. You create one with <code>go mod init github.com\/you\/project<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>go.mod<\/code> lists the module path, the Go version and the dependencies with their versions. <code>go.sum<\/code> stores checksums (hashes) of each dependency, so Go can check that the downloaded code was not changed. Commit both files to Git. Our <a href=\"https:\/\/smitabharat.com\/blog\/go-dependencies-go-mod-go-sum\/\">Go dependencies post<\/a> explains them step by step.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q20. What do go run, go build and go install each do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These three commands all compile your code, but they put the result in different places.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Command<\/th><th>What it does<\/th><th>Use it for<\/th><\/tr><\/thead><tbody><tr><td><code>go run .<\/code><\/td><td>Builds in a temp folder and runs it<\/td><td>Quick tests while coding<\/td><\/tr><tr><td><code>go build<\/code><\/td><td>Builds a binary in the current folder<\/td><td>Making a file to deploy<\/td><\/tr><tr><td><code>go install<\/code><\/td><td>Builds and puts the binary in <code>$GOPATH\/bin<\/code><\/td><td>Installing command-line tools<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For example, <code>go install golang.org\/x\/tools\/cmd\/goimports@latest<\/code> installs a tool you can run from anywhere.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q21. What is the difference between new and make?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both are built-in functions, but they do different jobs. <code>new(T)<\/code> works for any type. It creates a zero value and returns a pointer, <code>*T<\/code>. <code>make<\/code> works only for slices, maps and channels. It sets up their inner structure and returns the value itself, not a pointer.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    p := new(int) \/\/ *int pointing to 0\n    *p = 7\n    fmt.Println(*p)\n\n    nums := make([]int, 2, 5) \/\/ slice: length 2, capacity 5\n    ages := make(map[string]int)\n    ages[\"Ravi\"] = 30\n    ch := make(chan string, 1) \/\/ buffered channel\n\n    fmt.Println(len(nums), cap(nums), ages, cap(ch))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>7\n2 5 map[Ravi:30] 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So if you used <code>new<\/code> on a map, you would get a pointer to a nil map, and writing to it would panic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q22. What is variable shadowing, and why can it cause bugs?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Shadowing happens when you declare a new variable with the same name in an inner block. The inner one hides the outer one, so changes inside do not reach the outer variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    total := 10\n    if true {\n        total := 99 \/\/ new variable, hides the outer total\n        fmt.Println(\"inside:\", total)\n    }\n    fmt.Println(\"outside:\", total) \/\/ still 10\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>inside: 99\noutside: 10<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The classic bug is <code>err<\/code> inside an <code>if<\/code> block with <code>:=<\/code>, so the outer <code>err<\/code> stays <code>nil<\/code>. To catch this, read your <code>:=<\/code> lines carefully and use linters such as <code>go vet<\/code> with the shadow analyzer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q23. How do labels work with break and continue in nested loops?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A plain <code>break<\/code> only stops the innermost loop. To stop or skip an outer loop, put a label before it and use <code>break Label<\/code> or <code>continue Label<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    grid := [][]int{{1, 2, 3}, {4, -1, 6}, {7, 8, 9}}\n\nSearch:\n    for row, line := range grid {\n        for col, value := range line {\n            if value &lt; 0 {\n                fmt.Println(\"negative found at\", row, col)\n                break Search \/\/ leave both loops at once\n            }\n        }\n    }\n    fmt.Println(\"done\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>negative found at 1 1\ndone<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q24. What changed for loop variables in Go 1.22?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Before Go 1.22, a <code>for<\/code> loop used one variable for all passes. So goroutines and closures created in the loop often saw only the last value. Since Go 1.22, each pass gets its own new variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    var printers []func()\n    for i := 1; i &lt;= 3; i++ {\n        printers = append(printers, func() { fmt.Print(i, \" \") })\n    }\n    for _, p := range printers {\n        p()\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 2 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">With Go 1.21 or older, this program printed <code>4 4 4<\/code>. The new rule applies when your <code>go.mod<\/code> says <code>go 1.22<\/code> or later.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q25. What do the go and toolchain lines in go.mod mean?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>go<\/code> line, such as <code>go 1.24<\/code>, sets the minimum Go version needed to build the module. It also turns on language features from that version, such as the new loop variable rule. Since Go 1.21, an older Go toolchain refuses to build a module that needs a newer version.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The optional <code>toolchain<\/code> line, such as <code>toolchain go1.25.3<\/code>, says which Go toolchain to use. If your installed Go is older, the <code>go<\/code> command can download the right one automatically.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Slices, Maps and Strings Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Data structure questions come up in every round. So prepare these Go interview questions with small programs, because many of them are &#8220;what does this print?&#8221; questions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q26. What is the difference between an array and a slice?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An array has a fixed length that is part of its type. So <code>[3]int<\/code> and <code>[4]int<\/code> are different types, and an array can never grow. A slice is a flexible view over an array. It has a length and a capacity, and it can grow with <code>append<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Array<\/th><th>Slice<\/th><\/tr><\/thead><tbody><tr><td>Length<\/td><td>Fixed, part of the type<\/td><td>Can change<\/td><\/tr><tr><td>Example type<\/td><td><code>[5]int<\/code><\/td><td><code>[]int<\/code><\/td><\/tr><tr><td>Passed to a function<\/td><td>Whole array is copied<\/td><td>Small header copied, data shared<\/td><\/tr><tr><td>Zero value<\/td><td>Array of zero values<\/td><td><code>nil<\/code><\/td><\/tr><tr><td>Used in real code<\/td><td>Rarely<\/td><td>Almost always<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So in real Go code, you use slices almost every time. Arrays are mostly used for fixed things, such as a 32-byte hash.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q27. What are the length and capacity of a slice?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The length, <code>len(s)<\/code>, is how many items the slice holds right now. The capacity, <code>cap(s)<\/code>, is how many items fit in the underlying array, counting from the start of the slice. You can only read or write up to the length, but <code>append<\/code> can use the spare capacity without new memory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    s := make([]int, 2, 5)\n    fmt.Println(len(s), cap(s), s)\n\n    s = append(s, 7)\n    fmt.Println(len(s), cap(s), s)\n\n    t := s[1:2] \/\/ capacity counts from index 1 to the end of the array\n    fmt.Println(len(t), cap(t), t)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2 5 [0 0]\n3 5 [0 0 7]\n1 4 [0]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q28. What happens when append needs more capacity?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the slice has spare capacity, <code>append<\/code> writes into the same array. If not, Go makes a new, bigger array, copies the old items into it and returns a slice that points to the new array. So the old and new slices stop sharing data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The new size is roughly double for small slices and grows by a smaller factor for big ones. The exact rule can change between Go versions, so do not depend on it. Always use the result, as in <code>s = append(s, x)<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    a := []int{1, 2, 3} \/\/ len 3, cap 3, no spare room\n    b := append(a, 4)   \/\/ needs a new array\n    b[0] = 100\n    fmt.Println(a, b) \/\/ a is not changed\n    fmt.Println(cap(b) &gt; cap(a))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 2 3] [100 2 3 4]\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q29. Why can two slices change each other&#8217;s data?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A slice does not hold the data itself. It holds a pointer to an array, a length and a capacity. When you slice a slice, or copy a slice variable, both point to the same array. So writing through one changes what the other sees.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    marks := []int{50, 60, 70, 80}\n    top := marks[2:] \/\/ shares the same array\n    top[0] = 99\n    fmt.Println(marks, top)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[50 60 99 80] [99 80]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This also happens when you pass a slice to a function. The function can change the items, but if it appends past the capacity, the caller will not see the new items.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q30. How do you copy a slice safely?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use the built-in <code>copy<\/code> function into a new slice of the right length, or use <code>slices.Clone<\/code> (Go 1.21+). Both give you a separate array, so changes do not leak back.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"slices\"\n)\n\nfunc main() {\n    original := []string{\"go\", \"rust\", \"java\"}\n\n    copyA := make([]string, len(original))\n    n := copy(copyA, original) \/\/ returns how many items were copied\n    copyB := slices.Clone(original)\n\n    copyA[0] = \"GO\"\n    copyB[1] = \"RUST\"\n    fmt.Println(n, original, copyA, copyB)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3 [go rust java] [GO rust java] [go RUST java]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q31. What is a nil slice, and how is it different from an empty slice?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A nil slice, <code>var s []int<\/code>, has no underlying array, and <code>s == nil<\/code> is true. An empty slice, <code>s := []int{}<\/code>, has an array with zero items, so <code>s == nil<\/code> is false. Both have length 0, and you can <code>range<\/code> over and <code>append<\/code> to both.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The main difference shows up in JSON. A nil slice encodes as <code>null<\/code>, and an empty slice encodes as <code>[]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"encoding\/json\"\n    \"fmt\"\n)\n\nfunc main() {\n    var nilSlice []int\n    emptySlice := []int{}\n\n    fmt.Println(nilSlice == nil, emptySlice == nil, len(nilSlice), len(emptySlice))\n\n    a, _ := json.Marshal(nilSlice)\n    b, _ := json.Marshal(emptySlice)\n    fmt.Println(string(a), string(b))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false 0 0\nnull []<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q32. How do you remove an item from a slice?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.21, the easiest way is <code>slices.Delete(s, i, i+1)<\/code>, which removes the item at index <code>i<\/code> and keeps the order. Before that, people wrote <code>append(s[:i], s[i+1:]...)<\/code>. If order does not matter, you can move the last item into the gap, which is faster.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"slices\"\n)\n\nfunc main() {\n    cities := []string{\"Pune\", \"Delhi\", \"Mumbai\", \"Goa\"}\n    cities = slices.Delete(cities, 1, 2) \/\/ remove \"Delhi\"\n    fmt.Println(cities)\n\n    nums := []int{10, 20, 30, 40}\n    i := 0\n    nums[i] = nums[len(nums)-1] \/\/ fast remove: order not kept\n    nums = nums[:len(nums)-1]\n    fmt.Println(nums)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[Pune Mumbai Goa]\n[40 20 30]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q33. What is a map, and what types can be map keys?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A map stores key-value pairs and finds a value by its key very fast, like a phone book. You create one with <code>make(map[string]int)<\/code> or a literal like <code>map[string]int{\"a\": 1}<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A key type must be comparable with <code>==<\/code>. So strings, numbers, booleans, pointers, channels, arrays and structs made of comparable fields can be keys. Slices, maps and functions cannot be keys, because they are not comparable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q34. Is map iteration order fixed?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. The order of a <code>range<\/code> loop over a map is not defined, and Go randomises it on purpose so you do not depend on it. If you need a fixed order, collect the keys, sort them and then loop.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"maps\"\n    \"slices\"\n)\n\nfunc main() {\n    stock := map[string]int{\"pen\": 5, \"book\": 2, \"bag\": 9}\n\n    keys := slices.Sorted(maps.Keys(stock)) \/\/ Go 1.23+\n    for _, k := range keys {\n        fmt.Println(k, stock[k])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>bag 9\nbook 2\npen 5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>fmt<\/code> package prints maps in sorted key order, which makes test output stable. However, a <code>range<\/code> loop never does.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q35. What happens if you write to a nil map?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reading from a nil map is safe and returns the zero value. However, writing to a nil map causes a panic: <code>assignment to entry in nil map<\/code>. So always create the map with <code>make<\/code> or a literal before you add keys.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var counts map[string]int \/\/ nil map\nfmt.Println(counts[\"go\"]) \/\/ 0, reading is fine\ncounts[\"go\"] = 1          \/\/ panic: assignment to entry in nil map\n\ncounts = make(map[string]int) \/\/ fix: create it first\ncounts[\"go\"] = 1              \/\/ works<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q36. How do you check if a key exists in a map?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use the &#8220;comma ok&#8221; form. The second value is <code>true<\/code> if the key is present. This matters because a missing key returns the zero value, which might look like a real value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    scores := map[string]int{\"Asha\": 0, \"Ravi\": 85}\n\n    if score, ok := scores[\"Asha\"]; ok {\n        fmt.Println(\"Asha found with\", score)\n    }\n    _, ok := scores[\"Meena\"]\n    fmt.Println(\"Meena found:\", ok)\n\n    delete(scores, \"Ravi\") \/\/ deleting a key\n    fmt.Println(len(scores))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha found with 0\nMeena found: false\n1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q37. Are maps safe for use by many goroutines?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Reading from many goroutines at once is fine, but if any goroutine writes while others read or write, it is a data race. The Go runtime often detects this and crashes with <code>fatal error: concurrent map writes<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are three common fixes. Protect the map with a <code>sync.Mutex<\/code>, use a <code>sync.RWMutex<\/code> when reads are much more common than writes, or use <code>sync.Map<\/code> for special cases such as a cache where keys are written once and read many times.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q38. Are strings mutable in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Strings are immutable, so you cannot change a byte in place. <code>s[0] = 'H'<\/code> does not compile. To change text, you build a new string, or convert to <code>[]byte<\/code> or <code>[]rune<\/code>, edit it and convert back.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    name := \"golang\"\n    b := []byte(name) \/\/ a copy you can change\n    b[0] = 'G'\n    fmt.Println(string(b), name)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Golang golang<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Because strings are immutable, they are safe to share between goroutines, and substrings can share memory without copying.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q39. How do you loop over a string by characters?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>range<\/code>. It decodes UTF-8 for you and gives the byte index and the rune (character) on each pass. A normal index loop, <code>for i := 0; i &lt; len(s); i++<\/code>, goes byte by byte, which breaks non-English text.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    for index, char := range \"\u0928\u092e\u0938\u094d\u0924\u0947\" {\n        fmt.Printf(\"%d:%c \", index, char)\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0:\u0928 3:\u092e 6:\u0938 9:\u094d 12:\u0924 15:\u0947<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So the index jumps by 3, because each of these Hindi characters takes 3 bytes in UTF-8.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q40. How do you build a long string efficiently?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>strings.Builder<\/code>. Adding strings with <code>+<\/code> in a loop creates a new string every time, which wastes memory and time. A builder grows one buffer and makes the final string once.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    var sb strings.Builder\n    for i := 1; i &lt;= 5; i++ {\n        fmt.Fprintf(&amp;sb, \"item%d,\", i)\n    }\n    result := strings.TrimSuffix(sb.String(), \",\")\n    fmt.Println(result)\n\n    fmt.Println(strings.Join([]string{\"a\", \"b\", \"c\"}, \"-\")) \/\/ for a ready slice\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>item1,item2,item3,item4,item5\na-b-c<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you know the final size, call <code>sb.Grow(n)<\/code> first to avoid extra copies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q41. What do the slices and maps packages in the standard library give you?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These generic packages were added in Go 1.21. They give you ready-made helpers, so you do not write the same loops again and again.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Package<\/th><th>Useful functions<\/th><\/tr><\/thead><tbody><tr><td><code>slices<\/code><\/td><td><code>Sort<\/code>, <code>SortFunc<\/code>, <code>Contains<\/code>, <code>Index<\/code>, <code>Max<\/code>, <code>Min<\/code>, <code>Reverse<\/code>, <code>Equal<\/code>, <code>Clone<\/code>, <code>Delete<\/code>, <code>Insert<\/code>, <code>Compact<\/code><\/td><\/tr><tr><td><code>maps<\/code><\/td><td><code>Clone<\/code>, <code>Copy<\/code>, <code>Equal<\/code>, <code>DeleteFunc<\/code>, and since Go 1.23 <code>Keys<\/code>, <code>Values<\/code>, <code>All<\/code> (iterators)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"slices\"\n)\n\nfunc main() {\n    nums := []int{40, 10, 30, 10}\n    slices.Sort(nums)\n    fmt.Println(nums, slices.Contains(nums, 30), slices.Max(nums))\n    fmt.Println(slices.Compact(nums)) \/\/ removes repeated neighbours\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[10 10 30 40] true 40\n[10 30 40]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q42. What do the built-in min, max and clear functions do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These built-ins came in Go 1.21. <code>min<\/code> and <code>max<\/code> return the smallest or largest of their arguments, for any ordered type. <code>clear<\/code> empties a map, or sets every item of a slice to its zero value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(min(4, 2, 8), max(3.5, 1.2), min(\"pear\", \"apple\"))\n\n    cart := map[string]int{\"pen\": 2, \"book\": 1}\n    clear(cart)\n    fmt.Println(len(cart))\n\n    seats := []int{1, 2, 3}\n    clear(seats)\n    fmt.Println(seats, len(seats))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2 3.5 apple\n0\n[0 0 0] 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So <code>clear<\/code> on a slice keeps the length. It only resets the values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q43. How do you sort a slice of structs by a field?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>slices.SortFunc<\/code> with a compare function, or the older <code>sort.Slice<\/code>. The <code>cmp.Compare<\/code> helper returns -1, 0 or 1, which is exactly what <code>SortFunc<\/code> needs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"fmt\"\n    \"slices\"\n)\n\ntype Employee struct {\n    Name   string\n    Salary int\n}\n\nfunc main() {\n    staff := []Employee{{\"Ravi\", 50000}, {\"Asha\", 70000}, {\"Meena\", 60000}}\n\n    slices.SortFunc(staff, func(a, b Employee) int {\n        return cmp.Compare(b.Salary, a.Salary) \/\/ highest salary first\n    })\n    for _, e := range staff {\n        fmt.Println(e.Name, e.Salary)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha 70000\nMeena 60000\nRavi 50000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>slices.SortStableFunc<\/code> when items with equal values must keep their original order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q44. Is it possible to compare two slices or two maps with ==?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Slices and maps can only be compared with <code>nil<\/code>. Writing <code>a == b<\/code> for two slices does not compile. To compare contents, use <code>slices.Equal<\/code> and <code>maps.Equal<\/code>, or <code>reflect.DeepEqual<\/code> for nested data such as in tests.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"maps\"\n    \"slices\"\n)\n\nfunc main() {\n    fmt.Println(slices.Equal([]int{1, 2}, []int{1, 2}))\n    fmt.Println(maps.Equal(map[string]int{\"a\": 1}, map[string]int{\"a\": 2}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true\nfalse<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q45. Can structs be compared with ==, and can they be map keys?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, if all their fields are comparable. Two struct values are equal when every field is equal. Such structs can also be map keys, which is useful for keys made of two parts, like a grid point.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Point struct {\n    X, Y int\n}\n\nfunc main() {\n    fmt.Println(Point{1, 2} == Point{1, 2})\n\n    visited := map[Point]bool{}\n    visited[Point{3, 4}] = true\n    fmt.Println(visited[Point{3, 4}], visited[Point{0, 0}])\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true\ntrue false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If a struct has a slice, map or function field, <code>==<\/code> does not compile and the struct cannot be a map key.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Functions, Structs and Interface Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go interview questions cover how you organise code. Interfaces and method sets come up in almost every technical round, so give them extra time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q46. Can a Go function return more than one value?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A Go function can return any number of values. The most common pattern is returning a result and an error, so the caller can check if something went wrong.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nfunc divide(a, b float64) (float64, error) {\n    if b == 0 {\n        return 0, errors.New(\"cannot divide by zero\")\n    }\n    return a \/ b, nil\n}\n\nfunc main() {\n    result, err := divide(10, 4)\n    fmt.Println(result, err)\n\n    _, err = divide(1, 0)\n    fmt.Println(err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2.5 &lt;nil&gt;\ncannot divide by zero<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also name the return values, such as <code>func split(n int) (half, rest int)<\/code>. Named results are useful for short functions and for changing the result inside a <code>defer<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q47. What are variadic functions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A variadic function accepts any number of arguments of one type. You write <code>...<\/code> before the type of the last parameter, and inside the function it becomes a slice. <code>fmt.Println<\/code> and <code>append<\/code> are variadic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc sum(numbers ...int) int {\n    total := 0\n    for _, n := range numbers {\n        total += n\n    }\n    return total\n}\n\nfunc main() {\n    fmt.Println(sum())\n    fmt.Println(sum(1, 2, 3))\n\n    marks := []int{10, 20, 30}\n    fmt.Println(sum(marks...)) \/\/ spread a slice with ...\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0\n6\n60<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q48. What is a closure?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A closure is a function that uses variables from outside its own body. The function &#8220;remembers&#8221; those variables, even after the outer function has returned. So each closure can keep its own private state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ counter returns a function that remembers count.\nfunc counter() func() int {\n    count := 0\n    return func() int {\n        count++\n        return count\n    }\n}\n\nfunc main() {\n    next := counter()\n    fmt.Println(next(), next(), next())\n\n    other := counter() \/\/ a fresh, separate count\n    fmt.Println(other())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 2 3\n1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Closures are used for callbacks, middleware, goroutines and small helpers like <code>sort<\/code> compare functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q49. What does defer do, and in what order do deferred calls run?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>defer<\/code> schedules a function call to run when the surrounding function returns, whether it returns normally or panics. It is mostly used for clean-up, such as closing files, releasing locks and closing database rows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Deferred calls run in last in, first out (LIFO) order, like a stack of plates. So the last <code>defer<\/code> you write runs first.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    defer fmt.Println(\"first defer\")\n    defer fmt.Println(\"second defer\")\n    defer fmt.Println(\"third defer\")\n    fmt.Println(\"main body\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main body\nthird defer\nsecond defer\nfirst defer<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q50. When are a deferred call&#8217;s arguments evaluated?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The arguments are evaluated right away, when the <code>defer<\/code> line runs, not later when the call happens. So a deferred <code>fmt.Println(x)<\/code> prints the value <code>x<\/code> had at that moment. If you want the latest value, defer a closure instead.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 1\n    defer fmt.Println(\"defer with argument:\", x) \/\/ x is 1 here\n    defer func() { fmt.Println(\"defer with closure:\", x) }()\n    x = 2\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>defer with closure: 2\ndefer with argument: 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q51. What is a struct?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A struct is a type that groups related fields together, like a form with named boxes. For example, an <code>Employee<\/code> has a name, an age and a salary. Structs are how you model data in Go.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Employee struct {\n    Name   string\n    Age    int\n    Salary float64\n}\n\nfunc main() {\n    e := Employee{Name: \"Asha\", Age: 29, Salary: 75000}\n    e.Age++ \/\/ fields are reached with a dot\n    fmt.Println(e.Name, e.Age)\n    fmt.Printf(\"%+v\\n\", e) \/\/ %+v prints field names too\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha 30\n{Name:Asha Age:30 Salary:75000}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q52. What is struct embedding, and is it the same as inheritance?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding means putting one type inside a struct without a field name. The outer struct then gets the inner type&#8217;s fields and methods &#8220;promoted&#8221;, so you can call them directly. However, it is composition, not inheritance. The outer type is not a subtype of the inner one, and you cannot pass it where the inner type is expected.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Address struct {\n    City string\n}\n\nfunc (a Address) Label() string { return \"City: \" + a.City }\n\ntype Customer struct {\n    Name    string\n    Address \/\/ embedded, no field name\n}\n\nfunc main() {\n    c := Customer{Name: \"Ravi\", Address: Address{City: \"Pune\"}}\n    fmt.Println(c.City)    \/\/ promoted field\n    fmt.Println(c.Label()) \/\/ promoted method\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Pune\nCity: Pune<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So embedding is &#8220;has a&#8221; with a shortcut, while inheritance is &#8220;is a&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q53. What is a method, and what is a receiver?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A method is a function attached to a type. The receiver is the special parameter written before the method name, and it is the value the method works on. You can add methods to any type you define in your package, not just structs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Rectangle struct {\n    Width, Height float64\n}\n\n\/\/ (r Rectangle) is the receiver.\nfunc (r Rectangle) Area() float64 {\n    return r.Width * r.Height\n}\n\ntype Celsius float64\n\nfunc (c Celsius) Fahrenheit() float64 { return float64(c)*9\/5 + 32 }\n\nfunc main() {\n    fmt.Println(Rectangle{Width: 3, Height: 4}.Area())\n    fmt.Println(Celsius(100).Fahrenheit())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>12\n212<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q54. When should you use a pointer receiver instead of a value receiver?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A value receiver gets a copy, so changes inside the method are lost. A pointer receiver gets the address, so it can change the original value and avoids copying big structs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use a pointer receiver when the method changes the value, when the struct is large, or when it holds something that must not be copied, such as a <code>sync.Mutex<\/code>. Also, keep all methods on a type consistent. If one needs a pointer, make them all pointers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Wallet struct {\n    Balance int\n}\n\nfunc (w Wallet) AddCopy(amount int)     { w.Balance += amount } \/\/ changes a copy\nfunc (w *Wallet) AddPointer(amount int) { w.Balance += amount } \/\/ changes the original\n\nfunc main() {\n    w := Wallet{Balance: 100}\n    w.AddCopy(50)\n    fmt.Println(w.Balance)\n    w.AddPointer(50) \/\/ Go takes &amp;w for you\n    fmt.Println(w.Balance)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>100\n150<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q55. What is an interface?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An interface is a type that lists method signatures. Any type that has those methods can be used where the interface is expected. So an interface describes what something can do, not what it is.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, <code>io.Writer<\/code> has one method, <code>Write([]byte) (int, error)<\/code>. A file, a network connection, a buffer and an HTTP response all satisfy it, so <code>fmt.Fprintf<\/code> can write to any of them. Small interfaces like this are the Go style.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q56. How does a type implement an interface in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Implicitly. If a type has all the methods an interface lists, it satisfies that interface automatically. There is no <code>implements<\/code> keyword. So packages stay loosely connected, and you can define an interface later for types you do not own.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Shape interface {\n    Area() float64\n}\n\ntype Square struct{ Side float64 }\ntype Circle struct{ Radius float64 }\n\nfunc (s Square) Area() float64 { return s.Side * s.Side }\nfunc (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius }\n\nfunc main() {\n    shapes := []Shape{Square{Side: 2}, Circle{Radius: 1}}\n    for _, s := range shapes {\n        fmt.Printf(\"%T has area %.2f\\n\", s, s.Area())\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main.Square has area 4.00\nmain.Circle has area 3.14<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q57. What is the empty interface, and what is any?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The empty interface, <code>interface{}<\/code>, has no methods, so every type satisfies it. It can hold a value of any type. Since Go 1.18, <code>any<\/code> is a built-in alias for <code>interface{}<\/code>, so the two mean exactly the same thing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is useful for things like <code>fmt.Println(args ...any)<\/code> and decoding unknown JSON. However, you lose type safety, so prefer concrete types or generics when you can.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q58. What is a type assertion, and what is a type switch?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A type assertion gets the concrete value out of an interface, like <code>v.(string)<\/code>. Use the two-value form, <code>s, ok := v.(string)<\/code>, because the one-value form panics if the type is wrong. A type switch checks several types in one go.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc describe(v any) string {\n    switch x := v.(type) {\n    case int:\n        return fmt.Sprintf(\"int doubled is %d\", x*2)\n    case string:\n        return \"string of length \" + fmt.Sprint(len(x))\n    case nil:\n        return \"nil value\"\n    default:\n        return fmt.Sprintf(\"other type %T\", x)\n    }\n}\n\nfunc main() {\n    var v any = \"hello\"\n    s, ok := v.(string)\n    fmt.Println(s, ok)\n    _, ok = v.(int) \/\/ safe: no panic\n    fmt.Println(ok)\n\n    fmt.Println(describe(21))\n    fmt.Println(describe(\"go\"))\n    fmt.Println(describe(3.5))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>hello true\nfalse\nint doubled is 42\nstring of length 2\nother type float64<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q59. Why can an interface holding a nil pointer be non-nil?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An interface value has two parts: a type and a value. It is <code>nil<\/code> only when both parts are empty. If you store a nil <code>*MyError<\/code> in an <code>error<\/code>, the type part is set to <code>*MyError<\/code>, so the interface is not <code>nil<\/code>, even though the pointer inside is.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype MyError struct{}\n\nfunc (e *MyError) Error() string { return \"my error\" }\n\nfunc check(fail bool) error {\n    var p *MyError \/\/ nil pointer\n    if fail {\n        p = &amp;MyError{}\n    }\n    return p \/\/ wrong: always returns a non-nil interface\n}\n\nfunc main() {\n    err := check(false)\n    fmt.Println(err == nil)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So the fix is to return a plain <code>nil<\/code> when there is no error, not a typed nil pointer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q60. What are generics, and what is a type constraint?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generics, added in Go 1.18, let you write one function or type that works with many types. You add type parameters in square brackets, such as <code>[T any]<\/code>. A type constraint says which types are allowed for <code>T<\/code>. A constraint is an interface, such as <code>any<\/code>, <code>comparable<\/code> or <code>cmp.Ordered<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"fmt\"\n)\n\n\/\/ Largest works for any ordered type: ints, floats, strings.\nfunc Largest[T cmp.Ordered](items []T) T {\n    best := items[0]\n    for _, item := range items[1:] {\n        if item &gt; best {\n            best = item\n        }\n    }\n    return best\n}\n\n\/\/ Stack is a generic type.\ntype Stack[T any] struct{ items []T }\n\nfunc (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }\n\nfunc main() {\n    fmt.Println(Largest([]int{3, 9, 2}))\n    fmt.Println(Largest([]string{\"kiwi\", \"apple\", \"mango\"}))\n\n    var s Stack[string]\n    s.Push(\"a\")\n    s.Push(\"b\")\n    fmt.Println(s.items)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>9\nmango\n[a b]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q61. When should you use generics, and when an interface?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use generics when the code is the same for every type and only the type changes. Good examples are containers (stacks, sets, caches) and helpers like <code>Map<\/code>, <code>Filter<\/code> and <code>Max<\/code>. Use an interface when each type does the work in its own way, such as different <code>Shape<\/code> types each computing their own area.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A simple rule from the Go team is this. If you find yourself writing the exact same code several times with only the types different, think about generics. Otherwise, start with plain types and interfaces.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q62. Are function arguments passed by value or by reference?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go always passes arguments by value, which means the function gets a copy. However, some types hold a pointer inside. So copying a slice, map, channel, pointer or function value still lets the function reach the same underlying data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc changeInt(n int)            { n = 100 }\nfunc changePtr(n *int)           { *n = 100 }\nfunc changeSlice(s []int)        { s[0] = 100 }\nfunc changeMap(m map[string]int) { m[\"a\"] = 100 }\n\nfunc main() {\n    x, y := 1, 1\n    s := []int{1}\n    m := map[string]int{\"a\": 1}\n\n    changeInt(x)\n    changePtr(&amp;y)\n    changeSlice(s)\n    changeMap(m)\n    fmt.Println(x, y, s, m)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 100 [100] map[a:100]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So if a function must change a plain value like an <code>int<\/code> or a struct, pass a pointer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q63. What is a method set, and why does it matter for interfaces?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A method set is the list of methods that belong to a type. For a type <code>T<\/code>, the method set holds only methods with value receivers. For <code>*T<\/code>, it holds methods with both value and pointer receivers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This matters for interfaces. If a method has a pointer receiver, only <code>*T<\/code> satisfies the interface, not <code>T<\/code>. That is why <code>var s Saver = User{}<\/code> fails to compile when <code>Save<\/code> has a pointer receiver, but <code>var s Saver = &amp;User{}<\/code> works.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Saver interface{ Save() }\ntype User struct{ Name string }\n\nfunc (u *User) Save() {} \/\/ pointer receiver\n\nvar a Saver = &amp;User{} \/\/ works: *User has Save\nvar b Saver = User{}  \/\/ compile error: User does not implement Saver<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q64. Can you embed an interface inside another interface or a struct?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, both. Embedding interfaces inside an interface builds a bigger interface from smaller ones. For example, <code>io.ReadWriter<\/code> is <code>io.Reader<\/code> plus <code>io.Writer<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding an interface inside a struct gives the struct those methods, which are passed to whatever value you store in that field. This is handy for wrapping a type and overriding only one method, such as a logging wrapper around <code>http.ResponseWriter<\/code>. However, if the field is nil, calling a method panics.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Reader interface{ Read(p []byte) (int, error) }\ntype Writer interface{ Write(p []byte) (int, error) }\n\ntype ReadWriter interface { \/\/ interface embedding\n    Reader\n    Writer\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q65. What do the comparable constraint and ~int mean in generics?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>comparable<\/code> is a built-in constraint for types that support <code>==<\/code> and <code>!=<\/code>. You need it for map keys or for checking equality inside generic code. The <code>~<\/code> sign means &#8220;any type whose underlying type is this&#8221;. So <code>~int<\/code> allows <code>int<\/code> and also your own types like <code>type UserID int<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype UserID int\n\ntype Integer interface {\n    ~int | ~int64 \/\/ int, int64 and any type built on them\n}\n\nfunc Sum[T Integer](values []T) T {\n    var total T\n    for _, v := range values {\n        total += v\n    }\n    return total\n}\n\nfunc Index[T comparable](items []T, target T) int {\n    for i, item := range items {\n        if item == target { \/\/ needs comparable\n            return i\n        }\n    }\n    return -1\n}\n\nfunc main() {\n    fmt.Println(Sum([]UserID{10, 20, 30}))\n    fmt.Println(Index([]string{\"a\", \"b\", \"c\"}, \"c\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>60\n2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q66. What is range over a function (iterators), added in Go 1.23?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.23, a <code>for range<\/code> loop can loop over a function, called an iterator. The function receives a <code>yield<\/code> callback and calls it for each value. If <code>yield<\/code> returns <code>false<\/code>, the loop was stopped with <code>break<\/code>, so the iterator should stop too. The <code>iter<\/code> package names these types <code>iter.Seq[V]<\/code> and <code>iter.Seq2[K, V]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"iter\"\n)\n\n\/\/ Evens yields even numbers up to max.\nfunc Evens(max int) iter.Seq[int] {\n    return func(yield func(int) bool) {\n        for n := 0; n &lt;= max; n += 2 {\n            if !yield(n) {\n                return \/\/ the caller used break\n            }\n        }\n    }\n}\n\nfunc main() {\n    for n := range Evens(10) {\n        if n &gt; 6 {\n            break\n        }\n        fmt.Print(n, \" \")\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 2 4 6<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Standard helpers such as <code>slices.All<\/code>, <code>slices.Values<\/code> and <code>maps.Keys<\/code> return iterators too.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q67. What is reflection, and when should you avoid it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reflection, through the <code>reflect<\/code> package, lets a program look at types and values while it runs. For example, it can list a struct&#8217;s fields or read its tags. Packages like <code>encoding\/json<\/code> and many ORMs use it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, reflection is slower, harder to read and moves type errors from compile time to run time. So avoid it in normal business code. Use interfaces, type switches or generics first, and keep reflection for general-purpose libraries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q68. How do struct tags work under the hood?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A struct tag is a string written after a field, such as <code>json:\"user_name\"<\/code>. Go itself ignores tags. Packages read them at run time with reflection, through <code>reflect.StructField.Tag.Get(\"json\")<\/code>, and use them to change their behaviour.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\ntype User struct {\n    Name  string `json:\"user_name\" db:\"name\"`\n    Email string `json:\"email,omitempty\"`\n}\n\nfunc main() {\n    t := reflect.TypeOf(User{})\n    for i := 0; i &lt; t.NumField(); i++ {\n        field := t.Field(i)\n        fmt.Println(field.Name, \"json:\", field.Tag.Get(\"json\"), \"db:\", field.Tag.Get(\"db\"))\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Name json: user_name db: name\nEmail json: email,omitempty db:<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So <code>encoding\/json<\/code> reads the <code>json<\/code> tag, a database library reads the <code>db<\/code> tag, and a validator reads a <code>validate<\/code> tag.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Error Handling Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go handles errors as normal values. These Go interview questions test that idea, and interviewers often ask you to write a small custom error on the spot.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q69. Why does Go use error values instead of exceptions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, a function that can fail returns an <code>error<\/code> as its last value, and the caller checks it with <code>if err != nil<\/code>. There are no <code>try<\/code> and <code>catch<\/code> blocks. The Go team chose this so errors are visible right where they happen, and you cannot ignore them without noticing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes the control flow easy to follow, because there are no hidden jumps. The cost is more <code>if err != nil<\/code> lines, but each one is a clear decision about what to do with the failure.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    _, err := os.ReadFile(\"missing.txt\")\n    if err != nil {\n        fmt.Println(\"could not read file:\", err)\n        return\n    }\n    fmt.Println(\"file read\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>could not read file: open missing.txt: no such file or directory<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q70. How do you create a custom error type?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>error<\/code> is just an interface with one method, <code>Error() string<\/code>. So any type with that method is an error. A custom error type lets you carry extra data, such as a field name or an HTTP status.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\ntype ValidationError struct {\n    Field   string\n    Problem string\n}\n\nfunc (e *ValidationError) Error() string {\n    return e.Field + \": \" + e.Problem\n}\n\nfunc validateAge(age int) error {\n    if age &lt; 18 {\n        return &amp;ValidationError{Field: \"age\", Problem: \"must be 18 or more\"}\n    }\n    return nil\n}\n\nfunc main() {\n    err := validateAge(15)\n    fmt.Println(err)\n\n    var ve *ValidationError\n    if errors.As(err, &amp;ve) {\n        fmt.Println(\"bad field:\", ve.Field)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>age: must be 18 or more\nbad field: age<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For simple messages, <code>errors.New(\"text\")<\/code> or <code>fmt.Errorf(\"...\")<\/code> is enough.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q71. How do you wrap an error with %w?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Wrapping adds context to an error while keeping the original inside it. You use <code>fmt.Errorf<\/code> with the <code>%w<\/code> verb. Callers can still find the original with <code>errors.Is<\/code> or <code>errors.As<\/code>, and <code>errors.Unwrap<\/code> returns the inner error.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nvar ErrNotFound = errors.New(\"not found\")\n\nfunc findUser(id int) error {\n    return fmt.Errorf(\"find user %d: %w\", id, ErrNotFound)\n}\n\nfunc main() {\n    err := findUser(42)\n    fmt.Println(err)\n    fmt.Println(errors.Is(err, ErrNotFound))\n    fmt.Println(errors.Unwrap(err) == ErrNotFound)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>find user 42: not found\ntrue\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you use <code>%v<\/code> instead of <code>%w<\/code>, the text looks the same, but the chain is broken and <code>errors.Is<\/code> returns <code>false<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q72. What is the difference between errors.Is and errors.As?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>errors.Is<\/code> checks whether any error in the chain equals a specific value, usually a sentinel error like <code>io.EOF<\/code> or <code>sql.ErrNoRows<\/code>. <code>errors.As<\/code> checks whether any error in the chain has a specific type, and if so, it copies it into your variable so you can read its fields.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Function<\/th><th>Looks for<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td><code>errors.Is(err, target)<\/code><\/td><td>A specific error value<\/td><td><code>errors.Is(err, os.ErrNotExist)<\/code><\/td><\/tr><tr><td><code>errors.As(err, &amp;target)<\/code><\/td><td>A specific error type<\/td><td><code>errors.As(err, &amp;pathErr)<\/code> to read <code>pathErr.Path<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So use <code>Is<\/code> for &#8220;which error is it?&#8221; and <code>As<\/code> for &#8220;give me the details&#8221;. Both walk through wrapped errors, so never compare wrapped errors with <code>==<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q73. What does errors.Join do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>errors.Join<\/code>, added in Go 1.20, combines several errors into one. It is useful when you check many things and want to report all the problems, not just the first. <code>errors.Is<\/code> and <code>errors.As<\/code> still find each inner error.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nvar ErrNoName = errors.New(\"name is empty\")\nvar ErrBadAge = errors.New(\"age is negative\")\n\nfunc validate(name string, age int) error {\n    var errs []error\n    if name == \"\" {\n        errs = append(errs, ErrNoName)\n    }\n    if age &lt; 0 {\n        errs = append(errs, ErrBadAge)\n    }\n    return errors.Join(errs...) \/\/ nil if the slice is empty\n}\n\nfunc main() {\n    err := validate(\"\", -5)\n    fmt.Println(err)\n    fmt.Println(errors.Is(err, ErrBadAge))\n    fmt.Println(validate(\"Asha\", 30) == nil)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>name is empty\nage is negative\ntrue\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q74. What are panic and recover?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>panic<\/code> stops normal execution of the current goroutine. Deferred functions still run, and if nothing recovers, the program crashes with a stack trace. <code>recover<\/code> stops a panic, but it only works when called inside a deferred function.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc safeDivide(a, b int) (result int, err error) {\n    defer func() {\n        if r := recover(); r != nil {\n            err = fmt.Errorf(\"recovered: %v\", r)\n        }\n    }()\n    return a \/ b, nil \/\/ panics when b is 0\n}\n\nfunc main() {\n    fmt.Println(safeDivide(10, 2))\n    fmt.Println(safeDivide(1, 0))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>5 &lt;nil&gt;\n0 recovered: runtime error: integer divide by zero<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Also, a panic in one goroutine cannot be recovered by another goroutine. So each goroutine that might panic needs its own deferred <code>recover<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q75. When is it acceptable to panic?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Panic only for bugs and impossible states, not for normal errors. Normal problems, such as bad input, a missing file or a failed network call, should return an <code>error<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the usual acceptable cases.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A programming bug, such as an index out of range or a broken invariant.<\/li>\n\n\n<li>Setup that cannot fail in a correct program, such as <code>regexp.MustCompile<\/code> with a fixed pattern.<\/li>\n\n\n<li>Startup failures in <code>main<\/code>, where the app cannot run at all, although <code>log.Fatal<\/code> is more common there.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">HTTP servers in Go recover panics in handlers so one bad request does not crash the whole server. However, you should still fix the bug that caused it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q76. What is a sentinel error?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A sentinel error is a fixed, exported error value that callers can check for. Examples are <code>io.EOF<\/code>, <code>sql.ErrNoRows<\/code> and <code>os.ErrNotExist<\/code>. You create one at package level with <code>errors.New<\/code>, and the name usually starts with <code>Err<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var ErrInsufficientFunds = errors.New(\"insufficient funds\")\n\nfunc Withdraw(balance, amount int) error {\n    if amount &gt; balance {\n        return fmt.Errorf(\"withdraw %d: %w\", amount, ErrInsufficientFunds)\n    }\n    return nil\n}\n\n\/\/ Caller\nif errors.Is(err, ErrInsufficientFunds) {\n    \/\/ show a friendly message\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sentinel errors become part of your package API, so only export the ones callers really need to check.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q77. Should you log an error and also return it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usually no. If every layer logs and returns, one failure shows up five times in the logs, which makes them noisy and hard to read. The common rule is: handle the error once. Either deal with it (log it and continue, retry or use a fallback), or add context and return it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In a typical service, lower layers wrap and return errors. The top layer, such as the HTTP handler or <code>main<\/code>, logs the error once with the full context and decides what to send back to the user.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q78. How do you add useful context to an error without losing the original?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Wrap it with <code>fmt.Errorf<\/code> and <code>%w<\/code>, and add what you were doing and with which data, such as an ID or a file name. Keep the message short and lowercase, and do not repeat words like &#8220;error&#8221; or &#8220;failed&#8221; at every level.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"os\"\n)\n\nfunc loadConfig(path string) error {\n    _, err := os.ReadFile(path)\n    if err != nil {\n        return fmt.Errorf(\"load config %q: %w\", path, err)\n    }\n    return nil\n}\n\nfunc startApp() error {\n    if err := loadConfig(\"app.yaml\"); err != nil {\n        return fmt.Errorf(\"start app: %w\", err)\n    }\n    return nil\n}\n\nfunc main() {\n    err := startApp()\n    fmt.Println(err)\n    fmt.Println(\"file missing:\", errors.Is(err, os.ErrNotExist))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>start app: load config \"app.yaml\": open app.yaml: no such file or directory\nfile missing: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The message reads like a path from the top to the cause, and <code>errors.Is<\/code> still finds the original <code>os.ErrNotExist<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Concurrency Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Concurrency is the most asked topic in Go interviews. These Go interview questions cover goroutines, channels and the sync package, so practise each example until you can explain every line.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q79. What is a goroutine?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A goroutine is a function that runs at the same time as other functions, managed by the Go runtime. You start one by writing <code>go<\/code> before a function call. Goroutines are very light. Each one starts with a small stack of a few kilobytes that grows when needed, so one program can run thousands or even millions of them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    var wg sync.WaitGroup\n    results := make([]string, 3)\n\n    for i := 0; i &lt; 3; i++ {\n        wg.Add(1)\n        go func() { \/\/ runs at the same time as main\n            defer wg.Done()\n            results[i] = fmt.Sprintf(\"task %d done\", i)\n        }()\n    }\n    wg.Wait() \/\/ wait for all three goroutines\n    fmt.Println(results)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[task 0 done task 1 done task 2 done]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each goroutine writes to its own slot in the slice, so there is no data race, and the output order is fixed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q80. How is a goroutine different from an operating system thread?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A thread is managed by the operating system, and a goroutine is managed by the Go runtime. The runtime runs many goroutines on a small number of OS threads, so goroutines are much cheaper to create and switch between.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Goroutine<\/th><th>OS thread<\/th><\/tr><\/thead><tbody><tr><td>Managed by<\/td><td>Go runtime scheduler<\/td><td>Operating system<\/td><\/tr><tr><td>Starting stack<\/td><td>A few kilobytes, grows as needed<\/td><td>Usually about 1 MB or more<\/td><\/tr><tr><td>Cost to create<\/td><td>Very cheap<\/td><td>Much more expensive<\/td><\/tr><tr><td>Switching<\/td><td>Fast, in user space<\/td><td>Slower, needs the kernel<\/td><\/tr><tr><td>Typical count<\/td><td>Thousands to millions<\/td><td>Hundreds to a few thousand<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So in Go, you start a goroutine for each task and let the runtime map them onto threads.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-1024x640.png\" alt=\"Go interview questions comparison of goroutines and operating system threads\" class=\"wp-image-946\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Goroutines are cheap and managed by the Go runtime, while OS threads are heavier and managed by the operating system.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q81. What is the Go scheduler, and what do G, M and P mean?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Go scheduler decides which goroutine runs on which thread. It uses the GMP model.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>G (goroutine):<\/strong> a piece of work, with its own stack.<\/li>\n\n\n<li><strong>M (machine):<\/strong> an OS thread that actually runs code.<\/li>\n\n\n<li><strong>P (processor):<\/strong> a slot that holds a local run queue of goroutines. An M needs a P to run Go code. The number of Ps equals <code>GOMAXPROCS<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Each P has its own queue, so there is little locking. When a P runs out of work, it steals goroutines from another P, which keeps all CPUs busy. If a goroutine blocks on a system call, the M gives up its P, so another M can keep running other goroutines. Since Go 1.14, the scheduler can also pause long-running goroutines (preemption), so one busy loop cannot block others.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q82. What is a channel?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A channel is a typed pipe that goroutines use to send values to each other safely. You create one with <code>make(chan int)<\/code>, send with <code>ch &lt;- v<\/code> and receive with <code>v := &lt;-ch<\/code>. Channels also synchronise goroutines, because a send or receive can wait until the other side is ready.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    messages := make(chan string)\n\n    go func() {\n        messages &lt;- \"order 101 packed\" \/\/ send\n    }()\n\n    msg := &lt;-messages \/\/ receive: waits until a value arrives\n    fmt.Println(msg)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>order 101 packed<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also make send-only (<code>chan&lt;- int<\/code>) and receive-only (<code>&lt;-chan int<\/code>) channel types, which make function signatures clearer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q83. What is the difference between buffered and unbuffered channels?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An unbuffered channel, <code>make(chan int)<\/code>, has no storage. Here, a send waits until a receiver takes the value, so both sides meet at the same moment, like handing over a parcel in person. A buffered channel, <code>make(chan int, 3)<\/code>, holds up to 3 values. A send waits only when the buffer is full, and a receive waits only when it is empty, like a letterbox.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    jobs := make(chan string, 2) \/\/ buffered: room for 2\n    jobs &lt;- \"email\"              \/\/ does not wait\n    jobs &lt;- \"sms\"                \/\/ does not wait\n    fmt.Println(len(jobs), cap(jobs))\n\n    fmt.Println(&lt;-jobs, &lt;-jobs) \/\/ first in, first out\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2 2\nemail sms<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So use unbuffered channels when you want a guaranteed hand-off. Use buffered channels to smooth out short bursts or to limit work, as in a semaphore.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q84. What happens when you send to or receive from a closed channel?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sending to a closed channel causes a panic. Receiving from a closed channel never blocks. It returns any values still in the buffer, and after that it returns the zero value at once. The two-value receive tells you which case you have.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    ch := make(chan int, 2)\n    ch &lt;- 10\n    close(ch)\n\n    v, ok := &lt;-ch\n    fmt.Println(v, ok) \/\/ buffered value still there\n    v, ok = &lt;-ch\n    fmt.Println(v, ok) \/\/ closed and empty: zero value, false\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>10 true\n0 false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Also, closing a channel twice panics, and so does closing a nil channel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q85. Who should close a channel, and when?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The sender closes the channel, never the receiver, and only when no more values will be sent. Closing is a signal to receivers that the stream is finished, so a <code>for range<\/code> loop over the channel can end.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If many goroutines send on one channel, none of them should close it on its own. Instead, use a <code>sync.WaitGroup<\/code> and close the channel after all senders finish. Also, you do not have to close every channel. A channel that nobody ranges over is cleaned up by the garbage collector.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    results := make(chan int)\n    var wg sync.WaitGroup\n\n    for i := 1; i &lt;= 3; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            results &lt;- i * 10\n        }()\n    }\n\n    go func() {\n        wg.Wait()\n        close(results) \/\/ closed once, after every sender is done\n    }()\n\n    total := 0\n    for r := range results { \/\/ ends when results is closed\n        total += r\n    }\n    fmt.Println(\"total:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>total: 60<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q86. What does select do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>select<\/code> waits on several channel operations at once and runs the first one that is ready. If several are ready, it picks one at random. A <code>default<\/code> case makes it non-blocking, so it runs at once when no channel is ready.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    orders := make(chan string, 1)\n    alerts := make(chan string, 1)\n    alerts &lt;- \"low stock\"\n\n    select {\n    case o := &lt;-orders:\n        fmt.Println(\"order:\", o)\n    case a := &lt;-alerts:\n        fmt.Println(\"alert:\", a)\n    }\n\n    select {\n    case o := &lt;-orders:\n        fmt.Println(\"order:\", o)\n    default:\n        fmt.Println(\"nothing ready, moving on\")\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>alert: low stock\nnothing ready, moving on<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q87. How do you add a timeout to a channel operation?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>select<\/code> with a timer channel. <code>time.After(d)<\/code> sends a value after the given time, so if the result has not arrived by then, the timeout case runs. In real services, you usually use <code>ctx.Done()<\/code> from a context with a deadline.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    result := make(chan string)\n\n    go func() {\n        time.Sleep(200 * time.Millisecond) \/\/ slow work\n        result &lt;- \"report ready\"\n    }()\n\n    select {\n    case r := &lt;-result:\n        fmt.Println(r)\n    case &lt;-time.After(50 * time.Millisecond):\n        fmt.Println(\"timed out\")\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>timed out<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, the slow goroutine is left blocked forever, because nobody receives its value. Making <code>result<\/code> a buffered channel with size 1 lets it finish and exit, which avoids a leak.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q88. What is a WaitGroup, and what does wg.Go add in newer Go versions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>sync.WaitGroup<\/code> waits for a group of goroutines to finish. You call <code>Add(n)<\/code> before starting them, each goroutine calls <code>Done()<\/code> when finished, and <code>Wait()<\/code> blocks until the count reaches zero.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go 1.25 added <code>wg.Go(func())<\/code>. It calls <code>Add(1)<\/code>, starts the goroutine and calls <code>Done()<\/code> for you, so you cannot forget either step.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var wg sync.WaitGroup\nfor _, url := range urls {\n    wg.Go(func() { \/\/ Go 1.25+: Add and Done are handled for you\n        check(url)\n    })\n}\nwg.Wait()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A common bug is calling <code>wg.Add(1)<\/code> inside the goroutine. Then <code>Wait<\/code> might run before <code>Add<\/code>, and return too early.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q89. What is a Mutex, and what is an RWMutex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>sync.Mutex<\/code> is a lock that lets only one goroutine at a time into a piece of code. You call <code>Lock()<\/code> before touching shared data and release it after, usually with a deferred call. A <code>sync.RWMutex<\/code> allows many readers at the same time, but only one writer, and no readers while writing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\ntype Counter struct {\n    mu    sync.Mutex\n    count int\n}\n\nfunc (c *Counter) Increment() {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.count++\n}\n\nfunc main() {\n    var c Counter\n    var wg sync.WaitGroup\n    for i := 0; i &lt; 1000; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            c.Increment()\n        }()\n    }\n    wg.Wait()\n    fmt.Println(\"count:\", c.count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>count: 1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Without the mutex, the result would often be less than 1000, because increments would overwrite each other. Use <code>RWMutex<\/code> only when reads are much more common than writes, such as a config cache.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q90. What does sync.Once do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sync.Once<\/code> makes sure a function runs only one time, even if many goroutines call it at once. It is used for lazy setup, such as opening a shared connection or loading config on first use. Go 1.21 also added <code>sync.OnceFunc<\/code> and <code>sync.OnceValue<\/code> helpers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    var once sync.Once\n    var wg sync.WaitGroup\n    setup := func() { fmt.Println(\"loading config\") }\n\n    for i := 0; i &lt; 5; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            once.Do(setup) \/\/ only the first call runs setup\n        }()\n    }\n    wg.Wait()\n\n    getPort := sync.OnceValue(func() int { return 8080 })\n    fmt.Println(getPort(), getPort())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>loading config\n8080 8080<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q91. What are atomic operations?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Atomic operations, from <code>sync\/atomic<\/code>, read or change a single value in one step that cannot be interrupted. So they are safe across goroutines without a mutex, and they are faster for simple things like counters and flags. Since Go 1.19, typed values such as <code>atomic.Int64<\/code> and <code>atomic.Bool<\/code> make them easy to use.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"sync\/atomic\"\n)\n\nfunc main() {\n    var requests atomic.Int64\n    var wg sync.WaitGroup\n\n    for i := 0; i &lt; 500; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            requests.Add(1)\n        }()\n    }\n    wg.Wait()\n    fmt.Println(\"requests:\", requests.Load())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>requests: 500<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use atomics for one value. When you must update several fields together, use a mutex.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q92. What is a data race, and how do you find one?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A data race happens when two goroutines access the same memory at the same time, at least one of them writes, and there is no synchronisation. The results are unpredictable, and bugs may appear only sometimes, which makes them hard to find.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has a built-in race detector. Run <code>go test -race .\/...<\/code> or <code>go run -race main.go<\/code>, and it prints the exact lines where the conflicting reads and writes happened. Run your tests with <code>-race<\/code> in CI. To fix a race, use a mutex, an atomic value or a channel, so only one goroutine owns the data at a time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q93. What is a deadlock, and when does Go detect it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A deadlock happens when goroutines wait for each other forever, so none can move on. A simple example is sending on an unbuffered channel when nobody will ever receive.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func main() {\n    ch := make(chan int)\n    ch &lt;- 1 \/\/ nobody receives, so main waits forever\n}\n\n\/\/ fatal error: all goroutines are asleep - deadlock!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go detects a deadlock only when every goroutine in the program is blocked. If even one goroutine is still running, such as an HTTP server, the runtime cannot tell, and the stuck goroutines just hang. So use timeouts, contexts and a consistent lock order to avoid deadlocks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q94. What is a goroutine leak, and how do you prevent it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A goroutine leak happens when a goroutine never finishes, usually because it waits forever on a channel or a lock. Leaked goroutines keep their memory, so in a long-running server the count grows until the service slows down or crashes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are ways to prevent leaks.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Give every goroutine a clear way to stop, such as a cancelled <code>context<\/code> or a closed channel.<\/li>\n\n\n<li>Use buffered channels when a sender might be left with no receiver, such as after a timeout.<\/li>\n\n\n<li>Always set timeouts on network calls.<\/li>\n\n\n<li>Watch the goroutine count with <code>runtime.NumGoroutine()<\/code> or the pprof goroutine profile, and test with <code>go.uber.org\/goleak<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q95. What is the context package used for?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>context<\/code> package carries three things across function calls and goroutines: a deadline or timeout, a cancel signal and request-scoped values such as a request ID. When the context is cancelled, every function that watches <code>ctx.Done()<\/code> can stop its work early.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc slowQuery(ctx context.Context) error {\n    select {\n    case &lt;-time.After(500 * time.Millisecond): \/\/ the real work\n        return nil\n    case &lt;-ctx.Done(): \/\/ cancelled or timed out\n        return ctx.Err()\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)\n    defer cancel() \/\/ always call cancel to free resources\n\n    err := slowQuery(ctx)\n    fmt.Println(err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>context deadline exceeded<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Pass <code>ctx<\/code> as the first parameter of functions that do I\/O, and never store it inside a struct. Our <a href=\"https:\/\/smitabharat.com\/blog\/go-context-interview-questions-part-17\/\">Go context interview questions<\/a> cover it in detail.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q96. How do you build a worker pool in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A worker pool starts a fixed number of goroutines that read jobs from one channel and send results to another. So you control how much work runs at once, instead of starting a goroutine for every job.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    jobs := make(chan int, 10)\n    results := make(chan int, 10)\n    var wg sync.WaitGroup\n\n    for w := 1; w &lt;= 3; w++ { \/\/ 3 workers\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for n := range jobs {\n                results &lt;- n * n \/\/ the \"work\": square the number\n            }\n        }()\n    }\n\n    for n := 1; n &lt;= 5; n++ {\n        jobs &lt;- n\n    }\n    close(jobs) \/\/ workers exit when jobs run out\n\n    wg.Wait()\n    close(results)\n\n    sum := 0\n    for r := range results {\n        sum += r\n    }\n    fmt.Println(\"sum of squares:\", sum)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>sum of squares: 55<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q97. What are fan-out and fan-in patterns?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fan-out means starting several goroutines that read from the same channel, so the work is spread across them. Fan-in means merging results from several channels into one channel. A worker pool uses fan-out, and collecting all worker outputs into one channel is fan-in.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n    \"sync\"\n)\n\n\/\/ merge combines many channels into one (fan-in).\nfunc merge(inputs ...&lt;-chan string) &lt;-chan string {\n    out := make(chan string)\n    var wg sync.WaitGroup\n    for _, in := range inputs {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for v := range in {\n                out &lt;- v\n            }\n        }()\n    }\n    go func() { wg.Wait(); close(out) }()\n    return out\n}\n\nfunc producer(name string, count int) &lt;-chan string {\n    ch := make(chan string)\n    go func() {\n        defer close(ch)\n        for i := 1; i &lt;= count; i++ {\n            ch &lt;- fmt.Sprintf(\"%s-%d\", name, i)\n        }\n    }()\n    return ch\n}\n\nfunc main() {\n    var all []string\n    for v := range merge(producer(\"A\", 2), producer(\"B\", 2)) {\n        all = append(all, v)\n    }\n    sort.Strings(all) \/\/ arrival order varies, so sort\n    fmt.Println(all)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[A-1 A-2 B-1 B-2]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q98. What does &#8220;do not communicate by sharing memory&#8221; mean?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The full Go saying is: &#8220;Do not communicate by sharing memory; instead, share memory by communicating.&#8221; It means you should pass data between goroutines through channels, so only one goroutine owns the data at a time, instead of many goroutines reading and writing the same variable with locks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, it is a guideline, not a strict rule. A mutex is often simpler for protecting a shared counter or cache. So use channels to pass ownership of data or signal events, and use a mutex to guard shared state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q99. What is errgroup, and how is it different from a WaitGroup?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>errgroup<\/code> comes from <code>golang.org\/x\/sync\/errgroup<\/code>. Like a <code>WaitGroup<\/code>, it waits for a group of goroutines. However, each goroutine returns an <code>error<\/code>, and <code>Wait()<\/code> returns the first error. With <code>errgroup.WithContext<\/code>, the first failure also cancels the shared context, so the other goroutines can stop early. <code>SetLimit(n)<\/code> caps how many run at once.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>g, ctx := errgroup.WithContext(ctx)\ng.SetLimit(5) \/\/ at most 5 at a time\n\nfor _, id := range orderIDs {\n    g.Go(func() error {\n        return syncOrder(ctx, id) \/\/ return an error to stop the group\n    })\n}\nif err := g.Wait(); err != nil {\n    return fmt.Errorf(\"sync orders: %w\", err)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So use a <code>WaitGroup<\/code> when goroutines cannot fail, and <code>errgroup<\/code> when they can.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q100. How do you limit how many goroutines run at the same time?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are three common ways. A worker pool starts a fixed number of goroutines. A buffered channel can work as a semaphore, where each goroutine sends before it starts and receives when it ends. And <code>errgroup<\/code> has <code>SetLimit<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"sync\/atomic\"\n)\n\nfunc main() {\n    limit := make(chan struct{}, 2) \/\/ at most 2 at once\n    var running, maxSeen atomic.Int32\n    var wg sync.WaitGroup\n\n    for i := 0; i &lt; 6; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            limit &lt;- struct{}{}        \/\/ take a slot (waits if full)\n            defer func() { &lt;-limit }() \/\/ give the slot back\n\n            now := running.Add(1)\n            for {\n                old := maxSeen.Load()\n                if now &lt;= old || maxSeen.CompareAndSwap(old, now) {\n                    break\n                }\n            }\n            running.Add(-1)\n        }()\n    }\n    wg.Wait()\n    fmt.Println(\"never more than 2 at once:\", maxSeen.Load() &lt;= 2)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>never more than 2 at once: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q101. What is sync.Cond, and when would you use it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sync.Cond<\/code> lets goroutines wait until some condition becomes true, and lets another goroutine wake them up. <code>Wait()<\/code> releases the lock and sleeps, <code>Signal()<\/code> wakes one waiter, and <code>Broadcast()<\/code> wakes all of them. Waiters must check the condition in a loop, because they may wake up before it is true.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is rarely needed in everyday code, because channels usually do the job more simply. It is useful when many goroutines wait for the same state change, such as a queue that is no longer empty or a cache that has finished loading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q102. How do you build a rate limiter in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The easiest way is the token bucket in <code>golang.org\/x\/time\/rate<\/code>. You create a limiter with a rate and a burst size, then call <code>Wait(ctx)<\/code> to block until a token is free, or <code>Allow()<\/code> to check without waiting.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>limiter := rate.NewLimiter(rate.Limit(10), 20) \/\/ 10 per second, bursts up to 20\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    if !limiter.Allow() {\n        http.Error(w, \"too many requests\", http.StatusTooManyRequests)\n        return\n    }\n    \/\/ handle the request\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For a simple fixed pace, you can also use a <code>time.Ticker<\/code> and wait on its channel before each call. For limits shared by many servers, keep the counters in Redis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q103. What happens to running goroutines when main returns?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When <code>main<\/code> returns, the whole program exits at once. All other goroutines are stopped immediately, even in the middle of their work, and their deferred calls do not run. So a goroutine that writes a file or sends a message may never finish.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    go func() {\n        time.Sleep(100 * time.Millisecond)\n        fmt.Println(\"this never prints\")\n    }()\n    fmt.Println(\"main is done\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main is done<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That is why you wait for goroutines with a <code>WaitGroup<\/code>, a channel or <code>errgroup<\/code> before <code>main<\/code> returns.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q104. How do you test concurrent code, for example with testing\/synctest?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, always run tests with <code>-race<\/code>, so the race detector checks every test. Then avoid <code>time.Sleep<\/code> in tests, because it makes them slow and flaky. Instead, wait on channels or <code>WaitGroup<\/code>s, and pass timeouts through <code>context<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go 1.25 added the <code>testing\/synctest<\/code> package. Inside <code>synctest.Test<\/code>, code runs in a &#8220;bubble&#8221; with a fake clock. Time moves forward instantly when all goroutines in the bubble are blocked, so a test of a 5-second timeout finishes in microseconds and gives the same result every time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestTimeout(t *testing.T) {\n    synctest.Test(t, func(t *testing.T) {\n        ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)\n        defer cancel()\n\n        time.Sleep(5 * time.Second) \/\/ fake clock: instant\n        synctest.Wait()             \/\/ wait until goroutines settle\n        if ctx.Err() != context.DeadlineExceeded {\n            t.Fatal(\"expected timeout\")\n        }\n    })\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q105. Why must you never copy a sync.Mutex after first use?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>sync.Mutex<\/code> holds its lock state inside the struct. If you copy it, the copy gets a snapshot of that state, so two goroutines might lock two different mutexes and both enter the protected code. The same rule applies to <code>WaitGroup<\/code>, <code>Once<\/code>, <code>Cond<\/code> and atomic types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This often happens by accident with value receivers or by passing a struct by value. So use pointer receivers on types that hold a mutex, and run <code>go vet<\/code>, whose <code>copylocks<\/code> check reports these copies.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Cache struct {\n    mu   sync.Mutex\n    data map[string]string\n}\n\nfunc (c Cache) Get(k string) string { \/\/ wrong: copies the mutex\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    return c.data[k]\n}\n\nfunc (c *Cache) Set(k, v string) { \/\/ right: pointer receiver\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.data[k] = v\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Standard Library, Testing and Tooling Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Backend roles expect you to build, test and ship real services. So these Go interview questions cover <code>net\/http<\/code>, JSON, testing and the <code>go<\/code> command.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q106. How do you write a simple HTTP server with net\/http?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You register handler functions on a <code>ServeMux<\/code> and start the server with <code>http.ListenAndServe<\/code>. Since Go 1.22, patterns can include the HTTP method and path variables, such as <code>\"GET \/users\/{id}\"<\/code>, so simple APIs do not need a third-party router.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net\/http\"\n)\n\nfunc main() {\n    mux := http.NewServeMux()\n\n    mux.HandleFunc(\"GET \/hello\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintln(w, \"Hello, Go!\")\n    })\n\n    mux.HandleFunc(\"GET \/users\/{id}\", func(w http.ResponseWriter, r *http.Request) {\n        id := r.PathValue(\"id\") \/\/ read the path variable\n        fmt.Fprintf(w, \"user %s\\n\", id)\n    })\n\n    log.Println(\"listening on :8080\")\n    log.Fatal(http.ListenAndServe(\":8080\", mux))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each request runs in its own goroutine, so the server handles many clients at the same time. In production, use an <code>http.Server<\/code> with timeouts, as shown in the next answer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q107. How do you set timeouts on an HTTP server and client?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The default server and client have no timeouts, so a slow client or a slow API can hold a goroutine forever. Always set them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Server timeouts\nsrv := &amp;http.Server{\n    Addr:              \":8080\",\n    Handler:           mux,\n    ReadHeaderTimeout: 5 * time.Second,  \/\/ time to read request headers\n    ReadTimeout:       10 * time.Second, \/\/ time to read the whole request\n    WriteTimeout:      15 * time.Second, \/\/ time to write the response\n    IdleTimeout:       60 * time.Second, \/\/ keep-alive connections\n}\n\n\/\/ Client timeout for the whole request\nclient := &amp;http.Client{Timeout: 5 * time.Second}\n\n\/\/ Per-request deadline with context\nctx, cancel := context.WithTimeout(ctx, 2*time.Second)\ndefer cancel()\nreq, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\nresp, err := client.Do(req)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So the client timeout covers the whole call, and the context deadline lets the caller cancel early.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q108. How do JSON struct tags work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>encoding\/json<\/code> reads the <code>json<\/code> tag on each exported field to decide the key name and options. Without a tag, it uses the field name as it is. Unexported (lowercase) fields are always skipped.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Tag<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td><code>json:\"user_name\"<\/code><\/td><td>Use <code>user_name<\/code> as the key<\/td><\/tr><tr><td><code>json:\"email,omitempty\"<\/code><\/td><td>Skip the field if it has the zero value<\/td><\/tr><tr><td><code>json:\"-\"<\/code><\/td><td>Never encode or decode this field<\/td><\/tr><tr><td><code>json:\"id,string\"<\/code><\/td><td>Encode a number as a JSON string<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"encoding\/json\"\n    \"fmt\"\n)\n\ntype User struct {\n    Name     string `json:\"name\"`\n    Email    string `json:\"email,omitempty\"`\n    Password string `json:\"-\"`\n    Age      int    `json:\"age\"`\n}\n\nfunc main() {\n    data, _ := json.Marshal(User{Name: \"Asha\", Password: \"secret\", Age: 29})\n    fmt.Println(string(data))\n\n    var u User\n    err := json.Unmarshal([]byte(`{\"name\":\"Ravi\",\"email\":\"ravi@example.com\",\"age\":31}`), &amp;u)\n    fmt.Println(u.Name, u.Email, u.Age, err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{\"name\":\"Asha\",\"age\":29}\nRavi ravi@example.com 31 &lt;nil&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q109. How do you read a file line by line?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Open the file with <code>os.Open<\/code> and wrap it in a <code>bufio.Scanner<\/code>. The scanner reads one line at a time, so even a huge file uses little memory. Always check <code>scanner.Err()<\/code> at the end.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\nfunc main() {\n    \/\/ Create a small file for the example.\n    os.WriteFile(\"orders.txt\", []byte(\"pen,10\\nbook,250\\nbag,900\\n\"), 0644)\n    defer os.Remove(\"orders.txt\")\n\n    file, err := os.Open(\"orders.txt\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    defer file.Close()\n\n    scanner := bufio.NewScanner(file)\n    lineNo := 0\n    for scanner.Scan() {\n        lineNo++\n        parts := strings.Split(scanner.Text(), \",\")\n        fmt.Printf(\"line %d: item=%s price=%s\\n\", lineNo, parts[0], parts[1])\n    }\n    if err := scanner.Err(); err != nil {\n        fmt.Println(\"read error:\", err)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>line 1: item=pen price=10\nline 2: item=book price=250\nline 3: item=bag price=900<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">By default, a line can be up to 64 KB. For longer lines, call <code>scanner.Buffer<\/code> with a bigger size.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q110. How do you write a unit test with go test?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Put tests in a file ending with <code>_test.go<\/code>, in the same package. Each test is a function named <code>TestXxx<\/code> that takes <code>*testing.T<\/code>. Run them with <code>go test .\/...<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ file: mathx\/add.go\npackage mathx\n\nfunc Add(a, b int) int { return a + b }\n\n\/\/ file: mathx\/add_test.go\npackage mathx\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {\n    got := Add(2, 3)\n    want := 5\n    if got != want {\n        t.Errorf(\"Add(2, 3) = %d, want %d\", got, want)\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>t.Errorf<\/code> reports a failure and keeps going, while <code>t.Fatalf<\/code> stops that test at once. Use <code>go test -v<\/code> to see each test name and <code>go test -cover<\/code> to see coverage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q111. What are table-driven tests?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Table-driven tests put many test cases in a slice of structs, then loop over them. So adding a new case is one line, and every case runs the same checks. Calling <code>t.Run<\/code> gives each case its own name in the output.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestGrade(t *testing.T) {\n    tests := []struct {\n        name  string\n        marks int\n        want  string\n    }{\n        {\"top score\", 95, \"A\"},\n        {\"good score\", 80, \"B\"},\n        {\"low score\", 40, \"C\"},\n    }\n\n    for _, tc := range tests {\n        t.Run(tc.name, func(t *testing.T) {\n            if got := grade(tc.marks); got != tc.want {\n                t.Errorf(\"grade(%d) = %q, want %q\", tc.marks, got, tc.want)\n            }\n        })\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is the standard testing style in Go, and the Go standard library uses it everywhere.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q112. How do you write a benchmark?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A benchmark is a function named <code>BenchmarkXxx<\/code> that takes <code>*testing.B<\/code>. Since Go 1.24, the simplest form is a <code>for b.Loop()<\/code> loop, which handles the timing for you. Run benchmarks with <code>go test -bench=. -benchmem<\/code> to see time and memory per operation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func BenchmarkJoin(b *testing.B) {\n    parts := []string{\"a\", \"b\", \"c\", \"d\"}\n    for b.Loop() { \/\/ Go 1.24+; older code uses for i := 0; i &lt; b.N; i++\n        _ = strings.Join(parts, \",\")\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The output shows ns\/op (time per operation), B\/op (bytes allocated) and allocs\/op. Compare two versions with the <code>benchstat<\/code> tool, because one run can be noisy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q113. What is fuzz testing in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fuzz testing, built in since Go 1.18, feeds random and changed inputs into your function to find crashes and edge cases you did not think of. A fuzz test is named <code>FuzzXxx<\/code> and takes <code>*testing.F<\/code>. You add a few seed inputs, and the fuzzer creates new ones from them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func FuzzReverse(f *testing.F) {\n    f.Add(\"hello\") \/\/ seed input\n    f.Fuzz(func(t *testing.T, s string) {\n        twice := Reverse(Reverse(s))\n        if twice != s {\n            t.Errorf(\"Reverse twice changed %q to %q\", s, twice)\n        }\n    })\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run it with <code>go test -fuzz=FuzzReverse<\/code>. When the fuzzer finds a failing input, it saves it under <code>testdata\/fuzz<\/code>, so it becomes a normal test case from then on.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q114. What do go vet and gofmt do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>gofmt<\/code> formats your code in the one standard Go style: tabs, spacing and alignment. So every Go project looks the same, and code reviews skip style arguments. <code>goimports<\/code> does the same and also fixes import lines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>go vet<\/code> looks for likely bugs that still compile. Examples are wrong <code>Printf<\/code> verbs, copied mutexes, unreachable code and struct tags with typos. Run both in your editor and in CI. Many teams also add <code>staticcheck<\/code> or <code>golangci-lint<\/code> for more checks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q115. How do you run tests with the race detector?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Add the <code>-race<\/code> flag: <code>go test -race .\/...<\/code>. The race detector watches memory access while the tests run and reports any data race with the stack traces of both goroutines. You can also use <code>go run -race<\/code> and <code>go build -race<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It makes programs slower and use more memory, so it is for tests and staging, not normal production builds. It only finds races in code that actually runs, so good test coverage matters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q116. How do you manage dependencies and versions with Go modules?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go modules use semantic versions, such as <code>v1.4.2<\/code>. You add or upgrade a dependency with <code>go get example.com\/lib@v1.4.2<\/code>, or <code>@latest<\/code>. The version goes into <code>go.mod<\/code>, and checksums go into <code>go.sum<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the key rules.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go uses Minimal Version Selection: it picks the lowest version that meets every requirement, so builds are repeatable.<\/li>\n\n\n<li>A new major version, v2 or above, has a different import path, such as <code>example.com\/lib\/v2<\/code>.<\/li>\n\n\n<li><code>go list -m -u all<\/code> shows available upgrades, and <code>govulncheck .\/...<\/code> checks for known security issues.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q117. What is the internal directory used for?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Packages inside a folder named <code>internal<\/code> can only be imported by code in the parent of that folder. For example, <code>myapp\/internal\/db<\/code> can be used by <code>myapp\/cmd\/api<\/code>, but another module cannot import it. The Go tool enforces this.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So <code>internal<\/code> lets you keep helper code private and change it freely, without worrying about breaking other projects. Most Go services put almost all their code under <code>internal<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q118. What does go generate do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>go generate<\/code> runs commands written in special comments in your Go files, such as <code>\/\/go:generate stringer -type=Status<\/code>. It is used to create code automatically, for example mocks, <code>String()<\/code> methods for enums or code from <code>.proto<\/code> files.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not run during <code>go build<\/code>. You run it yourself, and you usually commit the generated files to Git, so others can build without the tools.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q119. How do you cross-compile for another operating system?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Set the <code>GOOS<\/code> and <code>GOARCH<\/code> environment variables before <code>go build<\/code>. Go includes everything it needs, so you do not have to install another compiler for pure Go code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>GOOS=linux GOARCH=amd64 go build -o app-linux .\/cmd\/api\nGOOS=windows GOARCH=amd64 go build -o app.exe .\/cmd\/api\nGOOS=darwin GOARCH=arm64 go build -o app-mac .\/cmd\/api<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run <code>go tool dist list<\/code> to see every supported pair. If your code uses cgo, cross-compiling is harder, because you also need a C compiler for the target.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q120. What does the log\/slog package give you?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>log\/slog<\/code>, added in Go 1.21, gives you structured logging in the standard library. Each log line has a level (Debug, Info, Warn, Error), a message and key-value fields. A text handler prints <code>key=value<\/code> pairs, and a JSON handler prints JSON that log tools can search.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"log\/slog\"\n    \"os\"\n)\n\nfunc main() {\n    \/\/ Drop the time field so this example prints the same output each run.\n    opts := &amp;slog.HandlerOptions{\n        ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {\n            if a.Key == slog.TimeKey {\n                return slog.Attr{}\n            }\n            return a\n        },\n    }\n    logger := slog.New(slog.NewTextHandler(os.Stdout, opts))\n    logger.Info(\"user logged in\", \"user_id\", 42, \"method\", \"otp\")\n    logger.Warn(\"slow query\", \"ms\", 850)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>level=INFO msg=\"user logged in\" user_id=42 method=otp\nlevel=WARN msg=\"slow query\" ms=850<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can add common fields to every line with <code>logger.With(\"service\", \"orders\")<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q121. What is the embed package used for?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>embed<\/code> package puts files into your compiled binary at build time. You add a <code>\/\/go:embed<\/code> comment above a variable. So a web app can ship its HTML templates, CSS, SQL migrations or config defaults inside one binary, with nothing extra to copy.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \"embed\"\n\n\/\/go:embed templates\/*.html\nvar templates embed.FS\n\n\/\/go:embed version.txt\nvar version string\n\nfunc main() {\n    page, _ := templates.ReadFile(\"templates\/home.html\")\n    fmt.Println(version, len(page))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q122. What are build tags (build constraints)?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A build tag is a comment at the top of a file that decides when the file is included in a build. It uses the <code>\/\/go:build<\/code> line with simple logic, such as <code>\/\/go:build linux &amp;&amp; amd64<\/code> or <code>\/\/go:build integration<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They are used for code that only works on one operating system, for slow integration tests that run only with <code>go test -tags=integration<\/code>, and for debug-only code. Also, file names like <code>file_windows.go<\/code> act as a build constraint automatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q123. What is a Go workspace, and what is go.work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A workspace lets you work on several modules together on your machine. You create a <code>go.work<\/code> file with <code>go work init .\/api .\/shared<\/code>. Then changes in <code>shared<\/code> are used by <code>api<\/code> straight away, without publishing a new version.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is meant for local development, so most teams do not commit <code>go.work<\/code>. Before workspaces, people used <code>replace<\/code> lines in <code>go.mod<\/code>, which were easy to forget and commit by mistake.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q124. What does go mod tidy do, and what is vendoring?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>go mod tidy<\/code> cleans up <code>go.mod<\/code> and <code>go.sum<\/code>. It adds any module your code imports but is missing, and removes modules you no longer use. Run it before every commit that changes imports.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Vendoring, with <code>go mod vendor<\/code>, copies all dependency source code into a <code>vendor<\/code> folder inside your project. Then builds do not need to download anything. Some companies use it for offline builds or strict reviews of third-party code, but most projects rely on the module proxy instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q125. What is cgo, and what does CGO_ENABLED=0 do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">cgo lets Go code call C code, using <code>import \"C\"<\/code>. It is useful for using existing C libraries, such as SQLite. However, it makes builds slower, cross-compiling harder and the binary depends on C libraries on the target machine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Setting <code>CGO_ENABLED=0<\/code> turns cgo off, so you get a fully static pure Go binary. That binary can run in a tiny image like <code>scratch<\/code> or distroless. So most Go services are built with <code>CGO_ENABLED=0<\/code> for Docker.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q126. How do you write HTTP middleware in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Middleware is a function that takes an <code>http.Handler<\/code> and returns a new <code>http.Handler<\/code> that does something before or after calling the original. It is used for logging, authentication, request IDs, panic recovery and timing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"net\/http\"\n    \"net\/http\/httptest\"\n)\n\n\/\/ logging wraps any handler and prints the method and path.\nfunc logging(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        fmt.Println(\"before:\", r.Method, r.URL.Path)\n        next.ServeHTTP(w, r) \/\/ call the real handler\n        fmt.Println(\"after:\", r.URL.Path)\n    })\n}\n\nfunc hello(w http.ResponseWriter, r *http.Request) {\n    fmt.Fprint(w, \"hello\")\n}\n\nfunc main() {\n    handler := logging(http.HandlerFunc(hello))\n\n    \/\/ httptest lets us call the handler without a real network.\n    rec := httptest.NewRecorder()\n    req := httptest.NewRequest(\"GET\", \"\/greet\", nil)\n    handler.ServeHTTP(rec, req)\n    fmt.Println(\"response:\", rec.Body.String())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>before: GET \/greet\nafter: \/greet\nresponse: hello<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You chain middleware by wrapping, such as <code>logging(auth(mux))<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q127. How does connection pooling work in database\/sql?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>*sql.DB<\/code> is not one connection. It is a pool that opens connections when needed and reuses idle ones. It is safe for many goroutines, so you create it once at startup and share it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You tune it with four settings.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db, err := sql.Open(\"pgx\", dsn) \/\/ does not connect yet\nif err != nil {\n    log.Fatal(err)\n}\nif err := db.PingContext(ctx); err != nil { \/\/ check the connection\n    log.Fatal(err)\n}\ndb.SetMaxOpenConns(25)\ndb.SetMaxIdleConns(25)\ndb.SetConnMaxLifetime(30 * time.Minute)\ndb.SetConnMaxIdleTime(5 * time.Minute)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Always close <code>rows<\/code> with <code>defer rows.Close()<\/code>, because open rows keep a connection busy. Forgetting this is a common cause of &#8220;too many connections&#8221; errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q128. How do you prevent SQL injection in a Go service?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Never build SQL by joining strings with user input. Always use placeholders, so the database treats the input as data, not as SQL code. PostgreSQL drivers use <code>$1, $2<\/code>, and MySQL uses <code>?<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Wrong: user input becomes part of the SQL text\nquery := \"SELECT id FROM users WHERE email = '\" + email + \"'\"\n\n\/\/ Right: the value is sent separately from the SQL\nrow := db.QueryRowContext(ctx, \"SELECT id FROM users WHERE email = $1\", email)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For dynamic parts that cannot be placeholders, such as a sort column, check the value against a fixed allow-list. Also, give the database user only the permissions the service needs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Performance and Advanced Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Senior rounds check how well you understand memory, speed and project design. These are the last group of Go interview questions before the scenarios, and the answers here are what interviewers expect from experienced developers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q129. How does the Go garbage collector work, at a high level?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go uses a concurrent, tri-colour mark and sweep garbage collector. &#8220;Mark&#8221; finds every object that is still reachable from your variables, and &#8220;sweep&#8221; frees the rest. &#8220;Concurrent&#8221; means most of this work runs at the same time as your program, so pauses are very short, usually well under a millisecond.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The tri-colour idea works like this. White objects are not yet checked, grey objects are found but their children are not checked yet, and black objects are fully checked. When no grey objects are left, everything still white is garbage. A write barrier keeps this correct while your goroutines keep changing pointers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go&#8217;s collector does not move objects and is not generational. So the best way to reduce GC work is simple: allocate less. Our <a href=\"https:\/\/smitabharat.com\/blog\/go-performance-interview-questions-part-23\/\">Go memory and performance questions<\/a> go further.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q130. What is escape analysis?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Escape analysis is a check the compiler does to decide where each value lives. If a value is only used inside a function, it stays on the stack, which is fast and needs no garbage collection. If the value &#8220;escapes&#8221;, for example because you return a pointer to it or store it in a long-lived place, it moves to the heap.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func onStack() int {\n    x := 42 \/\/ stays on the stack\n    return x\n}\n\nfunc onHeap() *int {\n    x := 42 \/\/ escapes: we return its address\n    return &amp;x\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can see the compiler&#8217;s decisions with <code>go build -gcflags=-m<\/code>. It prints lines like <code>moved to heap: x<\/code>. This helps you find unexpected heap allocations in hot code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q131. What is the difference between the stack and the heap in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each goroutine has its own stack, which holds local variables and function call frames. Stack memory is very cheap, because it is freed automatically when a function returns. The heap is shared memory for values that must live longer, and the garbage collector cleans it.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Stack<\/th><th>Heap<\/th><\/tr><\/thead><tbody><tr><td>Owned by<\/td><td>One goroutine<\/td><td>The whole program<\/td><\/tr><tr><td>Speed<\/td><td>Very fast<\/td><td>Slower to allocate<\/td><\/tr><tr><td>Freed by<\/td><td>Function return<\/td><td>Garbage collector<\/td><\/tr><tr><td>Size<\/td><td>Starts small, grows as needed<\/td><td>Limited by memory<\/td><\/tr><tr><td>Decided by<\/td><td>Escape analysis<\/td><td>Escape analysis<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, you do not choose stack or heap yourself. The compiler decides, and your code works the same either way.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q132. How do you profile a Go program with pprof?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">pprof is Go&#8217;s built-in profiler. It shows where your program spends CPU time, which code allocates memory, and what every goroutine is doing. For a web service, import <code>net\/http\/pprof<\/code> and the profiles appear under <code>\/debug\/pprof\/<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import _ \"net\/http\/pprof\" \/\/ registers \/debug\/pprof handlers\n\nfunc main() {\n    \/\/ Serve pprof on a private port only, never on the public one.\n    go http.ListenAndServe(\"localhost:6060\", nil)\n    \/\/ ... start your real server\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then you collect and read a profile with the <code>go tool pprof<\/code> command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go tool pprof http:\/\/localhost:6060\/debug\/pprof\/profile?seconds=30   # CPU\ngo tool pprof http:\/\/localhost:6060\/debug\/pprof\/heap                 # memory\ngo tool pprof -http=:8081 cpu.prof                                   # web view with flame graph<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In tests, you can use <code>go test -cpuprofile cpu.prof -memprofile mem.prof -bench=.<\/code> to profile a benchmark.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q133. What does sync.Pool do, and when should you use it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sync.Pool<\/code> keeps a set of temporary objects that can be reused, so you allocate less and the garbage collector has less work. You <code>Get<\/code> an object, use it, reset it and <code>Put<\/code> it back. The pool may drop objects at any GC, so it is only for things that are cheap to rebuild.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"sync\"\n)\n\nvar bufferPool = sync.Pool{\n    New: func() any { return new(bytes.Buffer) }, \/\/ called when the pool is empty\n}\n\nfunc render(name string) string {\n    buf := bufferPool.Get().(*bytes.Buffer)\n    defer func() {\n        buf.Reset() \/\/ clean it before giving it back\n        bufferPool.Put(buf)\n    }()\n    buf.WriteString(\"Hello, \")\n    buf.WriteString(name)\n    return buf.String()\n}\n\nfunc main() {\n    fmt.Println(render(\"Asha\"))\n    fmt.Println(render(\"Ravi\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Hello, Asha\nHello, Ravi<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use it for busy paths that allocate the same kind of buffer again and again, such as JSON encoding in an HTTP handler. Measure first, because a pool adds complexity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q134. What does GOMAXPROCS control?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>GOMAXPROCS<\/code> sets how many OS threads can run Go code at the same time, which is the number of Ps in the scheduler. By default, it equals the number of CPU cores. Goroutines blocked in system calls do not count against it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.25, the runtime on Linux also respects the container&#8217;s CPU limit. So a pod limited to 2 CPUs gets <code>GOMAXPROCS=2<\/code>, even on a 64-core node, which avoids heavy CPU throttling. You can still set it yourself with the environment variable or <code>runtime.GOMAXPROCS(n)<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q135. How do you reduce memory allocations in a hot path?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, measure with a benchmark using <code>-benchmem<\/code> and a memory profile, so you fix the real problem. Then use these common techniques.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Pre-size slices and maps with <code>make([]T, 0, n)<\/code> and <code>make(map[K]V, n)<\/code>.<\/li>\n\n\n<li>Use <code>strings.Builder<\/code> or <code>bytes.Buffer<\/code> instead of <code>+<\/code> in loops.<\/li>\n\n\n<li>Reuse buffers with <code>sync.Pool<\/code>.<\/li>\n\n\n<li>Avoid converting between <code>string<\/code> and <code>[]byte<\/code> again and again.<\/li>\n\n\n<li>Pass small structs by value, so they can stay on the stack.<\/li>\n\n\n<li>Avoid <code>fmt.Sprintf<\/code> in very hot code, and use <code>strconv<\/code> instead.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"testing\"\n)\n\nfunc withoutSize(n int) []int {\n    var s []int\n    for i := 0; i &lt; n; i++ {\n        s = append(s, i)\n    }\n    return s\n}\n\nfunc withSize(n int) []int {\n    s := make([]int, 0, n) \/\/ one allocation up front\n    for i := 0; i &lt; n; i++ {\n        s = append(s, i)\n    }\n    return s\n}\n\nfunc main() {\n    a := testing.AllocsPerRun(100, func() { withoutSize(1000) })\n    b := testing.AllocsPerRun(100, func() { withSize(1000) })\n    fmt.Println(\"pre-sized uses fewer allocations:\", b &lt; a, \"| pre-sized allocs:\", b)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>pre-sized uses fewer allocations: true | pre-sized allocs: 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q136. How would you structure a large Go project?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There is no single official layout, but most large Go services follow a similar shape.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>myapp\/\n  cmd\/\n    api\/main.go        \/\/ one folder per binary\n    worker\/main.go\n  internal\/\n    orders\/            \/\/ one package per business area\n    payments\/\n    platform\/          \/\/ shared helpers: db, logging, config\n  api\/                 \/\/ OpenAPI or .proto files\n  migrations\/\n  go.mod<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the main rules. Keep <code>main.go<\/code> small, so it only wires things together. Group code by business feature, not by technical layer. Put private code in <code>internal<\/code>. Avoid a giant <code>utils<\/code> package, and keep packages small with clear names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q137. How do you shut down an HTTP server gracefully?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A graceful shutdown stops taking new requests, lets in-flight requests finish and then closes resources like the database. You listen for SIGINT and SIGTERM, then call <code>srv.Shutdown(ctx)<\/code> with a timeout.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\ndefer stop()\n\nsrv := &amp;http.Server{Addr: \":8080\", Handler: mux}\ngo func() {\n    if err := srv.ListenAndServe(); err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {\n        log.Fatal(err)\n    }\n}()\n\n&lt;-ctx.Done() \/\/ wait for Ctrl+C or a SIGTERM from Kubernetes\n\nshutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\ndefer cancel()\nif err := srv.Shutdown(shutdownCtx); err != nil {\n    log.Println(\"forced to stop:\", err)\n}\ndb.Close()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>ListenAndServe<\/code> returns <code>http.ErrServerClosed<\/code> after <code>Shutdown<\/code>, so do not treat that as an error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q138. How do you design a REST API in Go with clean layers?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Split each feature into three simple layers. Each layer has one job, so the code is easy to test and change.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Layer<\/th><th>Job<\/th><th>Knows about<\/th><\/tr><\/thead><tbody><tr><td>Handler<\/td><td>Read the HTTP request, validate input, write JSON and status codes<\/td><td>HTTP<\/td><\/tr><tr><td>Service<\/td><td>Business rules, such as &#8220;cannot cancel a shipped order&#8221;<\/td><td>Plain Go types<\/td><\/tr><tr><td>Repository<\/td><td>Read and write the database<\/td><td>SQL or ORM<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The handler calls the service, and the service calls the repository through a small interface. So you can test the service with a fake repository and no database. Also, return clear status codes (201 for created, 400 for bad input, 404 for not found) and a consistent error JSON shape.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q139. What does GOMEMLIMIT do, and how is it different from GOGC?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>GOGC<\/code> sets how often the GC runs, based on heap growth. The default is 100, which means &#8220;run when the heap has grown 100% since the last collection&#8221;. A higher value means fewer collections but more memory, and a lower value means the opposite.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>GOMEMLIMIT<\/code>, added in Go 1.19, sets a soft limit on total memory, such as <code>GOMEMLIMIT=900MiB<\/code>. As the program gets close to it, the GC runs more often to stay under the limit. So in a container with a 1 GiB limit, it helps prevent out-of-memory kills. Many teams set <code>GOMEMLIMIT<\/code> to about 90% of the container limit and leave <code>GOGC<\/code> at the default.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q140. What do the unique package and weak pointers give you?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>unique<\/code> package (Go 1.23) does interning. <code>unique.Make(v)<\/code> returns a small handle, and equal values always get the same handle. So you can store one copy of a repeated value, such as the same country name across a million records, and compare handles very quickly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>weak<\/code> package (Go 1.24) gives weak pointers with <code>weak.Make(p)<\/code>. A weak pointer does not keep its object alive. If nothing else points to the object, the GC can free it, and <code>wp.Value()<\/code> then returns <code>nil<\/code>. This is useful for caches that should not stop memory from being freed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"unique\"\n)\n\nfunc main() {\n    a := unique.Make(\"India\")\n    b := unique.Make(\"India\")\n    c := unique.Make(\"Japan\")\n\n    fmt.Println(a == b, a == c) \/\/ fast handle comparison\n    fmt.Println(a.Value())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false\nIndia<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q141. How do you make a Go binary smaller?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go binaries include the runtime, so even &#8220;hello world&#8221; is a few megabytes. You can shrink them in a few ways.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CGO_ENABLED=0 go build -trimpath -ldflags=\"-s -w\" -o app .\/cmd\/api<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>-ldflags=\"-s -w\"<\/code> removes the symbol table and debug info.<\/li>\n\n\n<li><code>-trimpath<\/code> removes your local file paths from the binary.<\/li>\n\n\n<li><code>CGO_ENABLED=0<\/code> gives a static binary that runs in a tiny <code>scratch<\/code> or distroless Docker image.<\/li>\n\n\n<li>Remove unused dependencies, because each one adds code.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Tools like UPX can compress the binary further, but startup gets slower and some security scanners flag it. So most teams stop at the flags above.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q142. gRPC or REST: when would you choose each in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both work well in Go. The choice depends on who calls your service.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>REST (JSON over HTTP)<\/th><th>gRPC (Protobuf over HTTP\/2)<\/th><\/tr><\/thead><tbody><tr><td>Best for<\/td><td>Public APIs, browsers, simple tools<\/td><td>Service-to-service calls<\/td><\/tr><tr><td>Speed<\/td><td>Good<\/td><td>Faster, smaller messages<\/td><\/tr><tr><td>Contract<\/td><td>Optional (OpenAPI)<\/td><td>Required <code>.proto<\/code> file<\/td><\/tr><tr><td>Streaming<\/td><td>Limited<\/td><td>Built in, both directions<\/td><\/tr><tr><td>Easy to test by hand<\/td><td>Yes, with curl<\/td><td>Needs tools like grpcurl<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So a common setup is REST for the frontend and partners, and gRPC between internal Go services. See our <a href=\"https:\/\/smitabharat.com\/blog\/go-grpc-interview-questions-part-22\/\">Go gRPC interview questions<\/a> for more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q143. How do you manage configuration and secrets in a Go service?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep configuration out of the code, as the twelve-factor app style suggests. Read settings from environment variables or a config file at startup, put them into one <code>Config<\/code> struct, check required values and stop with a clear error if something is missing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Config struct {\n    Port        string\n    DatabaseURL string\n}\n\nfunc LoadConfig() (Config, error) {\n    cfg := Config{\n        Port:        getEnv(\"PORT\", \"8080\"),\n        DatabaseURL: os.Getenv(\"DATABASE_URL\"),\n    }\n    if cfg.DatabaseURL == \"\" {\n        return Config{}, errors.New(\"DATABASE_URL is required\")\n    }\n    return cfg, nil\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For secrets, such as database passwords and API keys, use a secret manager like Vault, AWS Secrets Manager or Kubernetes Secrets. Never commit secrets to Git, and never print them in logs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Scenario Go Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For each scenario, explain what you would check first, and why. Interviewers care about your steps, not just the final answer, so these answers follow a clear &#8220;check, find, fix&#8221; order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q144. A Go service slowly uses more and more memory. How do you find the cause?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, confirm it is a real leak and not normal growth. Watch the heap size and goroutine count over a few hours in your metrics. If memory keeps rising and never drops after GC, something is holding on to it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, take two heap profiles some time apart and compare them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -o heap1.prof http:\/\/localhost:6060\/debug\/pprof\/heap\n# wait 30 minutes\ncurl -o heap2.prof http:\/\/localhost:6060\/debug\/pprof\/heap\ngo tool pprof -base heap1.prof heap2.prof   # shows what grew<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Common causes are a cache or map with no size limit or expiry, goroutine leaks, slices that keep a big array alive (for example <code>small := big[:10]<\/code>), unclosed response bodies or <code>rows<\/code>, and timers that are never stopped. Fix the cause, then add a limit, such as an LRU cache with a maximum size.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q145. Response times jumped after a deploy. How do you find the slow code?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, check what changed. Compare the new release with the old one: code, dependencies, config and database migrations. If users are hurting, roll back first and investigate after.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then look at the data. Check which endpoints got slower in your p95 and p99 latency metrics, and use distributed traces to see which step takes the extra time, such as a database query or an outside API. Next, take a 30-second CPU profile from a running pod with pprof and look at the flame graph for new hot functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Common causes are a missing database index after a migration, an N+1 query, a new call to a slow service without a timeout, extra logging in a hot loop, or a smaller connection pool. Finally, add a benchmark or a load test so the same problem is caught before the next deploy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q146. A program hangs forever under load. How do you debug it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A hang usually means goroutines are stuck waiting on a channel, a lock or a network call. So first, get a dump of all goroutines while it is stuck.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>With pprof: open <code>\/debug\/pprof\/goroutine?debug=2<\/code> to see every goroutine and the line it is waiting on.<\/li>\n\n\n<li>Without pprof: send <code>SIGQUIT<\/code> (Ctrl+\\ in a terminal), and Go prints all goroutine stacks before exiting.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Then look for many goroutines blocked at the same line. Typical causes are a channel send with no receiver, a mutex that was locked but never released, two locks taken in a different order (a deadlock), a full connection pool, or an HTTP call with no timeout. Fix the cause, add timeouts with <code>context<\/code> everywhere and run tests with <code>-race<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q147. You must process one million records quickly. How do you design it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not load everything into memory, and do not start one million goroutines. Instead, build a streaming pipeline with a fixed number of workers.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, read records in a stream, such as a CSV with <code>bufio.Scanner<\/code> or a database cursor, and send them into a buffered channel.<\/li>\n\n\n<li>Next, start a worker pool sized to the bottleneck, for example <code>runtime.NumCPU()<\/code> workers for CPU work, or more for I\/O work.<\/li>\n\n\n<li>Then batch writes, such as inserting 500 rows per query or using PostgreSQL <code>COPY<\/code>, because one query per record is slow.<\/li>\n\n\n<li>Also, collect errors without stopping everything, and log failed record IDs for a retry.<\/li>\n\n\n<li>Finally, make the job restartable by saving progress, such as the last processed ID.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    records := make(chan int, 100)\n    var processed sync.Map\n    var wg sync.WaitGroup\n\n    for w := 0; w &lt; 4; w++ { \/\/ fixed number of workers\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            batch := make([]int, 0, 250)\n            flush := func() {\n                for _, r := range batch {\n                    processed.Store(r, true) \/\/ stands in for one bulk insert\n                }\n                batch = batch[:0]\n            }\n            for r := range records {\n                batch = append(batch, r)\n                if len(batch) == cap(batch) {\n                    flush()\n                }\n            }\n            flush() \/\/ write the last small batch\n        }()\n    }\n\n    for id := 1; id &lt;= 1_000_000; id++ { \/\/ stream records in\n        records &lt;- id\n    }\n    close(records)\n    wg.Wait()\n\n    count := 0\n    processed.Range(func(_, _ any) bool { count++; return true })\n    fmt.Println(\"records processed:\", count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>records processed: 1000000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Measure the speed, then tune the number of workers and the batch size to what the database can take.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q148. Two goroutines update the same map and the app crashes. How do you fix it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The crash is <code>fatal error: concurrent map writes<\/code>, because Go maps are not safe for writes from several goroutines. First, confirm it with <code>go test -race<\/code> or <code>go run -race<\/code>, which shows the exact lines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then pick a fix. The usual one is to put a <code>sync.Mutex<\/code> (or <code>sync.RWMutex<\/code> if reads are much more common) next to the map and lock around every read and write. Another option is to give the map to one goroutine and send it updates through a channel. <code>sync.Map<\/code> also works, but it suits only special cases like caches written once and read many times.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\ntype SafeCounter struct {\n    mu     sync.Mutex\n    counts map[string]int\n}\n\nfunc (c *SafeCounter) Inc(key string) {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.counts[key]++\n}\n\nfunc main() {\n    c := SafeCounter{counts: map[string]int{}}\n    var wg sync.WaitGroup\n    for i := 0; i &lt; 100; i++ {\n        wg.Add(2)\n        go func() { defer wg.Done(); c.Inc(\"orders\") }()\n        go func() { defer wg.Done(); c.Inc(\"payments\") }()\n    }\n    wg.Wait()\n    fmt.Println(c.counts[\"orders\"], c.counts[\"payments\"])\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>100 100<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q149. Goroutine count keeps growing in production. How do you find the leak?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, confirm the trend with a metric of <code>runtime.NumGoroutine()<\/code>, which Prometheus Go clients export as <code>go_goroutines<\/code>. A healthy service goes up and down with traffic, while a leak only goes up.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, open <code>\/debug\/pprof\/goroutine?debug=1<\/code>. It groups goroutines by stack, so the leak shows up as one stack with thousands of copies. Then read that line of code and ask why the goroutine never ends.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Typical causes are a goroutine sending on a channel after the receiver gave up on a timeout, a <code>for<\/code> loop that never checks <code>ctx.Done()<\/code>, HTTP calls with no timeout, and tickers that are never stopped. Fix it by giving every goroutine an exit path, such as a cancelled context or a buffered channel, and add <code>goleak<\/code> checks to your tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q150. Your service must handle a sudden ten times traffic spike. What do you change?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, find the bottleneck under load, because scaling the wrong part does not help. Run a load test and watch CPU, memory, database connections and p99 latency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then make changes in layers.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Scale out:<\/strong> keep the service stateless and add pods with the Kubernetes Horizontal Pod Autoscaler.<\/li>\n\n\n<li><strong>Cache:<\/strong> put hot reads in Redis or a small in-memory cache, and use a CDN for static content.<\/li>\n\n\n<li><strong>Protect the database:<\/strong> add read replicas, tune the connection pool and add missing indexes.<\/li>\n\n\n<li><strong>Move slow work to a queue:<\/strong> send emails and reports to background workers.<\/li>\n\n\n<li><strong>Protect yourself:<\/strong> add rate limits, timeouts and circuit breakers, and shed low-priority traffic with HTTP 503 when overloaded.<\/li>\n\n\n<li><strong>Tune Go:<\/strong> set <code>GOMEMLIMIT<\/code>, check <code>GOMAXPROCS<\/code> matches the CPU limit, and profile the hottest endpoints.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, test the new setup at more than ten times the normal load, and add alerts so you see the next spike early. Our <a href=\"https:\/\/smitabharat.com\/blog\/system-design-interview-questions\/\">system design interview questions<\/a> cover these patterns in detail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hands-On Go Interview Questions Practice<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers love &#8220;what does this print?&#8221; questions. Here is one program that tests slices, maps and defer together. It covers questions 28, 29, 36 and 49.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ Slices: b shares the same array as a while it has room.\n    a := make([]int, 3, 4) \/\/ len 3, cap 4: [0 0 0]\n    b := append(a, 9)      \/\/ fits in the spare slot, so b uses a's array\n    b[0] = 7               \/\/ this also changes a[0]\n    fmt.Println(a, b)\n\n    \/\/ Maps: reading a missing key gives the zero value.\n    stock := map[string]int{\"pen\": 5}\n    count, found := stock[\"book\"]\n    fmt.Println(count, found)\n\n    \/\/ defer: calls run in reverse order when main returns.\n    for i := 1; i &lt;= 3; i++ {\n        defer fmt.Println(\"deferred\", i)\n    }\n    fmt.Println(\"end of main\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[7 0 0] [7 0 0 9]\n0 false\nend of main\ndeferred 3\ndeferred 2\ndeferred 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Because a had spare capacity, append wrote into the same array, so changing b[0] also changed a[0]. Reading a missing map key returns 0, and the second value tells you the key was not found. Finally, the three deferred calls run after &#8220;end of main&#8221;, newest first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, here is the most asked live coding task: add up numbers using several goroutines. It covers questions 79, 82 and 88.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ sumPart adds up one part of the slice and sends the result on a channel.\nfunc sumPart(numbers []int, results chan&lt;- int, wg *sync.WaitGroup) {\n    defer wg.Done() \/\/ tell the WaitGroup this worker is finished\n    total := 0\n    for _, n := range numbers {\n        total += n\n    }\n    results &lt;- total\n}\n\nfunc main() {\n    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n    results := make(chan int, 2) \/\/ room for both results, so no worker blocks\n    var wg sync.WaitGroup\n\n    half := len(numbers) \/ 2\n    wg.Add(2)\n    go sumPart(numbers[:half], results, &amp;wg) \/\/ first half: 1 to 5\n    go sumPart(numbers[half:], results, &amp;wg) \/\/ second half: 6 to 10\n\n    wg.Wait()      \/\/ wait for both goroutines\n    close(results) \/\/ no more values will be sent\n\n    grandTotal := 0\n    for partial := range results {\n        grandTotal += partial\n    }\n    fmt.Println(\"total:\", grandTotal)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>total: 55<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each goroutine adds up half of the slice and sends its result into a buffered channel. The WaitGroup waits until both are done, then main closes the channel and adds up the partial totals. In Go 1.25 and later, you can also write wg.Go(func() { &#8230; }), which calls Add and Done for you.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Interview Questions<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Saying Go has no pointers:<\/strong> it does, but it has no pointer arithmetic.<\/li>\n\n\n<li><strong>Forgetting that slices share arrays:<\/strong> always explain length, capacity and append.<\/li>\n\n\n<li><strong>Writing to a map from many goroutines:<\/strong> mention a mutex every time.<\/li>\n\n\n<li><strong>Returning a typed nil as an error:<\/strong> return a plain nil instead.<\/li>\n\n\n<li><strong>Starting goroutines with no way to stop them:<\/strong> use context or a done channel to avoid leaks.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Answering Go Interview Questions<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Give a one-line definition first,<\/strong> then a small code example.<\/li>\n\n\n<li><strong>Say &#8220;it depends&#8221; with reasons,<\/strong> such as mutex vs channel, then pick one.<\/li>\n\n\n<li><strong>Mention the tools,<\/strong> such as go vet, the race detector and pprof.<\/li>\n\n\n<li><strong>Keep code idiomatic:<\/strong> short names in small scopes, errors checked right away, gofmt style.<\/li>\n\n\n<li><strong>Use real numbers<\/strong> from your work, such as requests per second or memory saved.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise these Go interview questions, write a small URL checker. It should take five URLs, check them at the same time with goroutines, stop each check after two seconds with context.WithTimeout, and print the status for each. Hint: use a WaitGroup and a results slice indexed by position, so the output order stays the same.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/go.dev\/tour\/\">A Tour of Go<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/doc\/effective_go\">Effective Go<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/doc\/faq\">Go FAQ<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/ref\/mem\">The Go Memory Model<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go interview questions focus on basics, slices and maps, interfaces, errors and concurrency.<\/li>\n\n\n<li>Slices share arrays until append needs more room, and maps are not safe for concurrent writes.<\/li>\n\n\n<li>Interfaces are implemented implicitly, and a typed nil inside an interface is not nil.<\/li>\n\n\n<li>Goroutines are cheap, channels pass data, and mutexes protect shared state.<\/li>\n\n\n<li>Use context for cancellation, and the race detector and pprof to find problems.<\/li>\n\n\n<li>Every one of the 150 questions now has a full answer, with runnable code for most of them.<\/li>\n\n\n<li>Practise &#8220;what does this print?&#8221; programs, because they are very common.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now go deeper, one topic at a time. Start with <a href=\"https:\/\/smitabharat.com\/blog\/go-basics-interview-questions-part-1\/\">Go Basics Interview Questions for Freshers<\/a>, then follow the 8-week plan in <a href=\"https:\/\/smitabharat.com\/blog\/all-interview-questions\/\">all interview questions with a study path<\/a>. For live coding practice, use the <a href=\"https:\/\/smitabharat.com\/blog\/go-tricky-output-programs\/\">Go tricky output programs<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go interview questions are now common in backend, cloud and DevOps hiring, because many teams build their APIs, tools and microservices in Go. This&hellip;<\/p>\n","protected":false},"author":1,"featured_media":944,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[10],"tags":[95,11,77,126],"swapz_series":[],"class_list":["post-947","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-interview","tag-go-interview-questions","tag-go-lang","tag-intermediate","tag-interview-questions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Interview Questions: Most Asked with Answers<\/title>\n<meta name=\"description\" content=\"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-interview-questions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Interview Questions: Most Asked with Answers\" \/>\n<meta property=\"og:description\" content=\"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-interview-questions\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-11T04:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:23+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"93 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Interview Questions: 150 Most Asked, with Full Answers\",\"datePublished\":\"2026-10-11T04:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/\"},\"wordCount\":12376,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-interview-questions-featured.png\",\"keywords\":[\"Go Interview Questions\",\"Go Lang\",\"Intermediate\",\"Interview Questions\"],\"articleSection\":[\"Interview\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/\",\"name\":\"Go Interview Questions: Most Asked with Answers\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-interview-questions-featured.png\",\"datePublished\":\"2026-10-11T04:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:23+00:00\",\"description\":\"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-interview-questions-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-interview-questions-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Interview Questions featured image: basics to concurrency with answers\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-interview-questions\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Interview Questions: 150 Most Asked, with Full Answers\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Interview Questions: Most Asked with Answers","description":"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/","og_locale":"en_US","og_type":"article","og_title":"Go Interview Questions: Most Asked with Answers","og_description":"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.","og_url":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-11T04:30:00+00:00","article_modified_time":"2026-11-28T19:59:23+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"93 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Interview Questions: 150 Most Asked, with Full Answers","datePublished":"2026-10-11T04:30:00+00:00","dateModified":"2026-11-28T19:59:23+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/"},"wordCount":12376,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png","keywords":["Go Interview Questions","Go Lang","Intermediate","Interview Questions"],"articleSection":["Interview"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/","url":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/","name":"Go Interview Questions: Most Asked with Answers","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png","datePublished":"2026-10-11T04:30:00+00:00","dateModified":"2026-11-28T19:59:23+00:00","description":"Go interview questions with full answers, basic to advanced: slices, maps, interfaces, errors, goroutines, channels, performance and real scenarios.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-interview-questions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-interview-questions-featured.png","width":2400,"height":1260,"caption":"Go Interview Questions featured image: basics to concurrency with answers"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-interview-questions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Interview Questions: 150 Most Asked, with Full Answers"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/947","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=947"}],"version-history":[{"count":2,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/947\/revisions"}],"predecessor-version":[{"id":962,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/947\/revisions\/962"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/944"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=947"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=947"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=947"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=947"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}