{"id":952,"date":"2026-10-24T09:00:00","date_gmt":"2026-10-24T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/?p=952"},"modified":"2026-11-29T01:29:21","modified_gmt":"2026-11-28T19:59:21","slug":"golang-questions-and-answers","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/","title":{"rendered":"Golang Questions and Answers: 140 Interview Q&#038;A for 2026"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Golang questions and answers in this post cover everything interviewers ask most, from basic syntax to goroutines, REST APIs, microservices and system design. You get 140 questions in one place, each with a clear answer, and many with code you can run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is a fully rewritten, corrected and reorganised version of our earlier <a href=\"https:\/\/smitabharat.com\/blog\/go-lang-interview-questions-and-answers\/\">Go Lang interview questions and answers<\/a> post. For a shorter list with the top answers only, see <a href=\"https:\/\/smitabharat.com\/blog\/go-interview-questions\/\">Go interview questions<\/a>. For a full study plan, use <a href=\"https:\/\/smitabharat.com\/blog\/all-interview-questions\/\">all interview questions with a study path<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Is New in These Golang Questions and Answers?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We checked all the Golang questions and answers from the old post. So you can trust this version for real interviews.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Clean numbering:<\/strong> questions now run from Q1 to Q140 in one format, grouped by topic.<\/li>\n\n\n\n<li><strong>Fixed code:<\/strong> broken quotes and formatting are gone, and every full program was run with its real output shown.<\/li>\n\n\n\n<li><strong>Corrected answers:<\/strong> wrong or outdated points were fixed, for example Go has no <code>===<\/code> operator, and <code>new<\/code> and <code>init<\/code> are not keywords.<\/li>\n\n\n\n<li><strong>Up to date:<\/strong> answers match Go 1.27, including loop variables from Go 1.22, iterators from Go 1.23 and <code>wg.Go<\/code> from Go 1.25.<\/li>\n\n\n\n<li><strong>No duplicates:<\/strong> questions that were asked twice in the old post are merged into one better answer.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How to Use These Golang Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Do not read all 140 answers in one sitting. Instead, follow these steps.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, pick the section that matches your next interview round.<\/li>\n\n\n\n<li>Next, cover the answer and try to say it out loud in two or three sentences.<\/li>\n\n\n\n<li>Then, run the code examples yourself and change them a little.<\/li>\n\n\n\n<li>Finally, mark the questions you missed and repeat them after a few days.<\/li>\n<\/ol>\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\/golang-questions-and-answers-diagram-1-1024x640.png\" alt=\"Golang questions and answers diagram showing the eight topic sections from basics to system design\" class=\"wp-image-950\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">The questions move from Go basics and data structures to concurrency, performance, web APIs and system design.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below shows the sections and where each one starts.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Section<\/th><th>Topics<\/th><th>Questions<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td><a href=\"#golang-questions-and-answers-on-basics-and-syntax\">Basics and syntax<\/a><\/td><td>Q1 to Q22<\/td><\/tr><tr><td>2<\/td><td><a href=\"#golang-questions-and-answers-on-arrays-slices-maps-and-strings\">Arrays, slices, maps and strings<\/a><\/td><td>Q23 to Q32<\/td><\/tr><tr><td>3<\/td><td><a href=\"#golang-questions-and-answers-on-functions-structs-and-interfaces\">Functions, structs and interfaces<\/a><\/td><td>Q33 to Q48<\/td><\/tr><tr><td>4<\/td><td><a href=\"#golang-questions-and-answers-on-error-handling\">Error handling<\/a><\/td><td>Q49 to Q51<\/td><\/tr><tr><td>5<\/td><td><a href=\"#golang-questions-and-answers-on-goroutines-and-concurrency\">Goroutines and concurrency<\/a><\/td><td>Q52 to Q83<\/td><\/tr><tr><td>6<\/td><td><a href=\"#golang-questions-and-answers-on-memory-gc-and-performance\">Memory, GC and performance<\/a><\/td><td>Q84 to Q93<\/td><\/tr><tr><td>7<\/td><td><a href=\"#golang-questions-and-answers-on-web-rest-apis-and-security\">Web, REST APIs and security<\/a><\/td><td>Q94 to Q114<\/td><\/tr><tr><td>8<\/td><td><a href=\"#golang-questions-and-answers-on-microservices-system-design-and-tools\">Microservices, system design and tools<\/a><\/td><td>Q115 to Q140<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<div id=\"gq-filter-bar\" style=\"display:none;margin:16px 0;padding:12px 16px;border:1px solid #d0d7de;border-radius:8px;background:#f6f8fa;font-size:15px;\">Showing only: <strong id=\"gq-filter-name\"><\/strong> <button type=\"button\" id=\"gq-show-all\" class=\"gq-all\" style=\"margin-left:10px;padding:6px 14px;border:0;border-radius:6px;background:#00add8;color:#fff;cursor:pointer;font-size:14px;\">Show all topics<\/button><\/div>\n<style>\n#gq-nav{display:flex;flex-wrap:wrap;gap:10px;justify-content:space-between;align-items:center;margin:28px 0;padding:14px 16px;border:1px solid #d0d7de;border-radius:8px;background:#f6f8fa}\n#gq-nav a,#gq-nav button{display:inline-block;padding:9px 16px;border:0;border-radius:6px;background:#00add8;color:#fff !important;text-decoration:none !important;font-size:14px;line-height:1.3;cursor:pointer}\n#gq-nav button.gq-all{background:#57606a}\n#gq-nav .gq-sp{flex:1}\n<\/style>\n<script>\n(function(){\n  var ids = [\"golang-questions-and-answers-on-basics-and-syntax\",\"golang-questions-and-answers-on-arrays-slices-maps-and-strings\",\"golang-questions-and-answers-on-functions-structs-and-interfaces\",\"golang-questions-and-answers-on-error-handling\",\"golang-questions-and-answers-on-goroutines-and-concurrency\",\"golang-questions-and-answers-on-memory-gc-and-performance\",\"golang-questions-and-answers-on-web-rest-apis-and-security\",\"golang-questions-and-answers-on-microservices-system-design-and-tools\"];\n  var names = [\"Basics and syntax\",\"Arrays, slices, maps and strings\",\"Functions, structs and interfaces\",\"Error handling\",\"Goroutines and concurrency\",\"Memory, GC and performance\",\"Web, REST APIs and security\",\"Microservices, system design and tools\"];\n  function box(){\n    var b = document.getElementById('gq-filter-bar');\n    if (!b) return null;\n    return b.closest('.entry-content') || b.parentElement;\n  }\n  function goTop(el){ var go = function(){ var y = el.getBoundingClientRect().top + window.pageYOffset - 90; window.scrollTo(0, Math.max(0, y)); }; setTimeout(go, 30); setTimeout(go, 350); }\n  function apply(id){\n    var c = box(); if (!c) return;\n    var old = document.getElementById('gq-nav'); if (old) old.parentNode.removeChild(old);\n    var cur = null, h = null, endEl = null;\n    Array.prototype.forEach.call(c.children, function(el){\n      if (el.tagName === 'H2') {\n        if (h) { if (!endEl) endEl = el; }\n        cur = ids.indexOf(el.id) > -1 ? el.id : null;\n        if (el.id === id) h = el;\n      }\n      var hide = false;\n      if (id) { if (cur) { if (cur !== id) hide = true; } }\n      el.style.display = hide ? 'none' : '';\n    });\n    var bar = document.getElementById('gq-filter-bar');\n    bar.style.display = id ? 'block' : 'none';\n    if (!id) return;\n    if (!h) return;\n    var k = ids.indexOf(id);\n    document.getElementById('gq-filter-name').textContent = names[k];\n    var nav = document.createElement('div'); nav.id = 'gq-nav';\n    var out = '';\n    if (k > 0) out += '<a href=\"#' + ids[k-1] + '\">\\u2190 Previous: ' + names[k-1] + '<\/a>';\n    out += '<span class=\"gq-sp\"><\/span><button type=\"button\" class=\"gq-all\">Show all topics<\/button><span class=\"gq-sp\"><\/span>';\n    if (k < ids.length - 1) out += '<a href=\"#' + ids[k+1] + '\">Next: ' + names[k+1] + ' \\u2192<\/a>';\n    nav.innerHTML = out;\n    c.insertBefore(nav, endEl);\n    goTop(h);\n  }\n  function fromHash(){\n    var id = decodeURIComponent(location.hash.slice(1));\n    if (ids.indexOf(id) > -1) { apply(id); return; }\n    if (!id) return;\n    var el = document.getElementById(id);\n    if (el) { if (el.offsetParent === null) { apply(null); goTop(el); } }\n  }\n  document.addEventListener('click', function(e){\n    var t = e.target;\n    if (!t || !t.closest) return;\n    var lk = t.closest('#gq-nav a');\n    if (lk) {\n      e.preventDefault();\n      var nid = lk.getAttribute('href').slice(1);\n      history.pushState(null, '', '#' + nid);\n      apply(nid);\n      return;\n    }\n    if (!t.classList.contains('gq-all')) return;\n    history.replaceState(null, '', location.pathname + location.search);\n    apply(null);\n    var tbl = document.getElementById('gq-filter-bar').previousElementSibling;\n    if (tbl) goTop(tbl);\n  });\n  window.addEventListener('hashchange', fromHash);\n  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fromHash); else fromHash();\n})();\n<\/script>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Basics and Syntax<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Golang questions and answers cover the core building blocks of Go. If you are new to the language, start here because every later topic builds on them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is Go and why is it popular?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go (often called Golang) is an open-source programming language created at Google. It was designed for simplicity, fast compilation and easy concurrency. Today it is a top choice for cloud services, APIs and command-line tools.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the main reasons developers like it.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Simple syntax with only 25 keywords, so code is easy to read.<\/li>\n\n\n\n<li>Compiled to native machine code, so programs run fast.<\/li>\n\n\n\n<li>Built-in concurrency with goroutines and channels.<\/li>\n\n\n\n<li>Automatic garbage collection, so you do not free memory by hand.<\/li>\n\n\n\n<li>A strong standard library for HTTP, JSON, testing and more.<\/li>\n\n\n\n<li>A single static binary that is easy to ship in Docker images.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What are pointers in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A pointer is a variable that stores the memory address of another variable. So instead of holding the value itself, it points to where the value lives in memory. The type <code>*T<\/code> means &#8220;pointer to a value of type T&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use two operators with pointers.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>&amp;x<\/code> gives you the address of <code>x<\/code>.<\/li>\n\n\n\n<li><code>*p<\/code> reads or changes the value that <code>p<\/code> points to. This is called dereferencing.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small program that changes a value through a pointer.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    x := 10   \/\/ a normal int variable\n    p := &amp;x   \/\/ p holds the address of x (type *int)\n\n    fmt.Println(\"x =\", x)\n    fmt.Println(\"*p =\", *p) \/\/ read the value through the pointer\n\n    *p = 20 \/\/ change x through the pointer\n    fmt.Println(\"x after change =\", x)\n    fmt.Println(\"p points to x:\", p == &amp;x)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 10\n*p = 10\nx after change = 20\np points to x: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go pointers are safer than C pointers. For example, Go has no pointer arithmetic, so you cannot move a pointer to a random address. The zero value of a pointer is <code>nil<\/code>, and dereferencing a <code>nil<\/code> pointer causes a panic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. 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> allocates memory for any type, sets it to the zero value and returns a pointer <code>*T<\/code>. <code>make<\/code> works only for slices, maps and channels, and it returns a ready-to-use value, not a pointer.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>new<\/th><th>make<\/th><\/tr><\/thead><tbody><tr><td>Works with any type<\/td><td>Works only with slice, map and channel<\/td><\/tr><tr><td>Returns a pointer (<code>*T<\/code>)<\/td><td>Returns the value itself (<code>T<\/code>)<\/td><\/tr><tr><td>Memory is set to the zero value<\/td><td>Sets up the internal data structure<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ new returns a pointer to a zeroed int\n    count := new(int)\n    *count = 5\n    fmt.Println(\"count:\", *count)\n\n    \/\/ make builds a usable map and slice\n    ages := make(map&#91;string]int)\n    ages&#91;\"Asha\"] = 30\n    scores := make(&#91;]int, 3, 10) \/\/ length 3, capacity 10\n\n    fmt.Println(\"ages:\", ages)\n    fmt.Println(\"scores:\", scores, \"len:\", len(scores), \"cap:\", cap(scores))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>count: 5\nages: map&#91;Asha:30]\nscores: &#91;0 0 0] len: 3 cap: 10<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What are packages in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A package is a group of Go files in the same folder that are compiled together. Packages help you organise code and reuse it across projects. Every Go file starts with a <code>package<\/code> line that names its package.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The package <code>main<\/code> is special because it builds an executable program, and it must have a <code>func main()<\/code>. Other packages are libraries. Also, only names that start with a capital letter (like <code>Println<\/code>) are exported and visible to other packages.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \/\/ strings and fmt are packages from the standard library\n    fmt.Println(strings.ToUpper(\"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>Q5. Can Go functions return multiple values?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A Go function can return two or more values, and this is used everywhere in Go. The most common pattern returns a result plus an <code>error<\/code>, 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\n\/\/ divide returns the result and an error if b is zero\nfunc divide(a, b int) (int, 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, 2)\n    fmt.Println(result, err)\n\n    _, err = divide(5, 0)\n    fmt.Println(\"error:\", err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>5 &lt;nil&gt;\nerror: cannot divide by zero<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What are variadic functions, and how do you return multiple values from a variadic function?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A variadic function accepts any number of arguments of one type. You write it with three dots, like <code>nums ...int<\/code>. Inside the function, <code>nums<\/code> is simply a slice of <code>int<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can mix a variadic parameter with multiple return values freely. Keep these rules in mind.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Only the last parameter can be variadic.<\/li>\n\n\n\n<li>List the return values in parentheses, and you can give them names.<\/li>\n\n\n\n<li>The caller receives the results as separate variables.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ sumAndAvg returns both the sum and the average of any number of ints.\nfunc sumAndAvg(nums ...int) (sum int, avg float64) {\n    for _, n := range nums {\n        sum += n\n    }\n    if len(nums) &gt; 0 {\n        avg = float64(sum) \/ float64(len(nums))\n    }\n    return \/\/ named results sum and avg are returned\n}\n\nfunc main() {\n    s, a := sumAndAvg(3, 5, 7, 9)\n    fmt.Println(\"sum:\", s, \"avg:\", a)\n\n    \/\/ pass an existing slice with values...\n    values := &#91;]int{10, 20}\n    s, a = sumAndAvg(values...)\n    fmt.Println(\"sum:\", s, \"avg:\", a)\n\n    \/\/ calling with no arguments gives an empty slice\n    s, a = sumAndAvg()\n    fmt.Println(\"sum:\", s, \"avg:\", a)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>sum: 24 avg: 6\nsum: 30 avg: 15\nsum: 0 avg: 0<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Topic<\/th><th>Tip<\/th><\/tr><\/thead><tbody><tr><td>Named vs unnamed results<\/td><td>Named results allow a bare <code>return<\/code>. Unnamed results need <code>return v1, v2<\/code>.<\/td><\/tr><tr><td>Zero arguments<\/td><td>A call with no arguments gives an empty slice, so check <code>len(nums)<\/code> if needed.<\/td><\/tr><tr><td>Forwarding<\/td><td>To pass a slice into a variadic function, add <code>...<\/code> after it, like <code>f(vals...)<\/code>.<\/td><\/tr><tr><td>Performance<\/td><td>The arguments are packed into a slice. In very hot loops, passing a slice directly can be cheaper.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. What is dependency management in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go manages dependencies with modules. A module is described by a <code>go.mod<\/code> file, which lists the module path, the Go version and the required packages. Also, a <code>go.sum<\/code> file stores checksums so builds are safe and repeatable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the commands you use most often.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go mod init example.com\/app      # start a new module\ngo get github.com\/google\/uuid    # add or upgrade a dependency\ngo mod tidy                      # add missing and remove unused dependencies\ngo list -m all                   # list every module in the build<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.24, you can also track tool dependencies in <code>go.mod<\/code> with <code>go get -tool<\/code>. So the whole team uses the same versions of tools like linters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. Why do we use the underscore (_) in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The underscore is called the blank identifier. You can assign a value to it, but you can never read from it. This matters because Go does not allow unused variables or unused imports, so <code>_<\/code> lets you throw away values you do not need.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Use case<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Ignore an extra return value<\/td><td><code>_, err := someFunc()<\/code><\/td><\/tr><tr><td>Ignore the loop index or value<\/td><td><code>for _, v := range items<\/code><\/td><\/tr><tr><td>Import a package only for its side effects<\/td><td><code>import _ \"github.com\/lib\/pq\"<\/code><\/td><\/tr><tr><td>Check at compile time that a type implements an interface<\/td><td><code>var _ Shape = (*Circle)(nil)<\/code><\/td><\/tr><tr><td>Ignore a result on purpose<\/td><td><code>_ = file.Close()<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    fruits := &#91;]string{\"apple\", \"banana\", \"cherry\"}\n\n    \/\/ we do not need the index, so we use _\n    for _, fruit := range fruits {\n        fmt.Println(fruit)\n    }\n\n    \/\/ Println returns (int, error); keep only the byte count\n    n, _ := fmt.Println(\"Hello\")\n    fmt.Println(\"bytes written:\", n)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>apple\nbanana\ncherry\nHello\nbytes written: 6<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. What is the difference between declaring and initializing a variable in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Declaring a variable tells the compiler that the variable exists and what type it has. Initializing it means giving it a starting value. In Go, a declared variable without a value is never empty, because it always gets the zero value of its type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can declare and initialize in a few ways.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>var count int<\/code> declares only, so <code>count<\/code> is <code>0<\/code>.<\/li>\n\n\n\n<li><code>var name string = \"Go\"<\/code> declares and initializes together.<\/li>\n\n\n\n<li><code>city := \"Pune\"<\/code> is the short form. It works only inside functions, and Go infers the type.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    var count int          \/\/ declaration only, gets zero value 0\n    var name string = \"Go\" \/\/ declaration with initialization\n    city := \"Pune\"         \/\/ short declaration, type is inferred\n\n    fmt.Println(count, name, city)\n\n    count = 42 \/\/ assignment later\n    fmt.Println(count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 Go Pune\n42<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. Can we pass parameters to main() in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. The <code>main<\/code> function cannot take parameters, and it cannot return a value. Instead, you read command-line arguments from <code>os.Args<\/code>, which is a slice of strings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Args[0]<\/code> is the program path, and <code>os.Args[1:]<\/code> holds the real arguments. For example, you could run <code>go run . hello world<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    args := os.Args&#91;1:] \/\/ skip the program name\n    fmt.Println(\"number of args:\", len(args))\n    fmt.Println(\"args:\", args)\n\n    if len(args) &gt; 0 {\n        fmt.Println(\"first arg:\", args&#91;0])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>number of args: 2\nargs: &#91;hello world]\nfirst arg: hello<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For named options like <code>-port=8080<\/code>, use the <code>flag<\/code> package from the standard library. Also, to set an exit code, call <code>os.Exit(code)<\/code> instead of returning from <code>main<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. What is GOROOT in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">GOROOT is the folder where Go itself is installed. It holds the compiler, the tools and the standard library source. So when you import <code>fmt<\/code>, Go finds it under GOROOT.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You rarely need to set GOROOT yourself, because the <code>go<\/code> command works it out from its own location. You can check the value with this command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go env GOROOT<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do not confuse it with GOPATH. GOPATH is your workspace, and it stores the module cache and installed binaries (by default <code>$HOME\/go<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. What is a zero value in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A zero value is the default value Go gives a variable when you declare it without a value. This means Go has no uninitialized variables, so you never read random memory.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Type<\/th><th>Zero value<\/th><\/tr><\/thead><tbody><tr><td>int, float64 and other numbers<\/td><td><code>0<\/code><\/td><\/tr><tr><td>bool<\/td><td><code>false<\/code><\/td><\/tr><tr><td>string<\/td><td><code>\"\"<\/code> (empty string)<\/td><\/tr><tr><td>pointer, slice, map, channel, function, interface<\/td><td><code>nil<\/code><\/td><\/tr><tr><td>struct<\/td><td>every field set to its own zero value<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype User struct {\n    Name   string\n    Age    int\n    Active bool\n}\n\nfunc main() {\n    var n int\n    var ok bool\n    var s string\n    var nums &#91;]int\n    var u User\n\n    fmt.Println(n, ok, s == \"\", nums == nil)\n    fmt.Printf(\"%+v\\n\", u)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>0 false true true\n{Name: Age:0 Active:false}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q13. Why is Go fast?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go is fast both to build and to run. First, it compiles ahead of time to native machine code, so there is no interpreter or virtual machine. Next, its simple grammar and its dependency rules make compilation very quick.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the main reasons.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Static typing lets the compiler produce efficient code.<\/li>\n\n\n\n<li>Goroutines are lightweight, so a program can run many thousands of them.<\/li>\n\n\n\n<li>The garbage collector is concurrent with very short pauses.<\/li>\n\n\n\n<li>The runtime is small, so programs start quickly.<\/li>\n\n\n\n<li>Structs and arrays are laid out in memory compactly, which is friendly to CPU caches.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q14. What is the difference between the == and === operators in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no <code>===<\/code> operator. If you write <code>===<\/code> in Go code, the compiler gives a syntax error. The <code>===<\/code> operator comes from JavaScript, where it means strict equality without type conversion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, you only use <code>==<\/code> and <code>!=<\/code>. Because Go is strongly typed, <code>==<\/code> never converts types for you. So comparing an <code>int<\/code> with a <code>string<\/code> does not compile at all, and that is safer than JavaScript&#8217;s loose <code>==<\/code>.<\/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    a, b := 5, 5\n    fmt.Println(a == b) \/\/ same type, same value\n\n    fmt.Println(\"go\" == \"Go\") \/\/ strings are compared byte by byte\n\n    p1 := Point{1, 2}\n    p2 := Point{1, 2}\n    fmt.Println(p1 == p2) \/\/ structs compare field by field\n\n    \/\/ fmt.Println(5 == \"5\") would not compile: mismatched types\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true\nfalse\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For reference, this is how the two operators behave in JavaScript.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>5 == \"5\"    \/\/ true, the string is converted to a number\n5 === \"5\"   \/\/ false, the types are different<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Slices, maps and functions cannot be compared with <code>==<\/code> in Go, except against <code>nil<\/code>. To compare two slices, use <code>slices.Equal<\/code> from the standard library.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q15. Are there classes in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No, Go does not have classes or inheritance. Instead, you get the same results with a few simple tools.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Structs hold the data.<\/li>\n\n\n\n<li>Methods attached to a type give it behaviour.<\/li>\n\n\n\n<li>Interfaces describe behaviour, and types satisfy them automatically.<\/li>\n\n\n\n<li>Embedding and composition let you reuse code.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ User is like a class with fields\ntype User struct {\n    Name string\n    Age  int\n}\n\n\/\/ Greet is a method on User\nfunc (u User) Greet() string {\n    return \"Hi, I am \" + u.Name\n}\n\n\/\/ Birthday uses a pointer receiver so it can change the User\nfunc (u *User) Birthday() {\n    u.Age++\n}\n\nfunc main() {\n    u := User{Name: \"Smita\", Age: 25}\n    fmt.Println(u.Greet())\n    u.Birthday()\n    fmt.Println(\"new age:\", u.Age)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Hi, I am Smita\nnew age: 26<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q16. What are the categories of data types in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go data types are usually grouped into four categories for learning. The Go specification itself does not use the word &#8220;reference type&#8221;, but the grouping is still helpful.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Category<\/th><th>Types<\/th><\/tr><\/thead><tbody><tr><td>Basic<\/td><td><code>int<\/code>, <code>float64<\/code>, <code>complex128<\/code>, <code>string<\/code>, <code>bool<\/code>, <code>byte<\/code>, <code>rune<\/code><\/td><\/tr><tr><td>Composite (aggregate)<\/td><td>array, struct<\/td><\/tr><tr><td>Reference-like<\/td><td>pointer, slice, map, channel, function<\/td><\/tr><tr><td>Interface<\/td><td><code>interface<\/code> types such as <code>error<\/code> or <code>any<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The reference-like types hold a pointer to shared data inside them. So when you copy a slice or a map, both copies still see the same underlying data. However, Go always passes arguments by value, even for these types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q17. Can a class call another class inside it in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no <code>class<\/code> keyword, so there is no &#8220;class within a class&#8221;. Go prefers composition over inheritance. You still have three simple ways to make one type use another.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Composition: one struct has another struct as a named field.<\/li>\n\n\n\n<li>Embedding: you put a struct inside another without a field name, so its fields and methods are promoted. This feels a bit like inheritance, but it is not.<\/li>\n\n\n\n<li>Interfaces: a struct holds an interface field, so you can swap the real type later. This works well in large projects and in tests.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Engine struct {\n    Power int\n}\n\nfunc (e Engine) Start() string {\n    return fmt.Sprintf(\"engine with %d HP started\", e.Power)\n}\n\n\/\/ Car embeds Engine, so Car gets the Start method\ntype Car struct {\n    Engine\n    Brand string\n}\n\nfunc main() {\n    c := Car{Engine: Engine{Power: 150}, Brand: \"Tata\"}\n    fmt.Println(c.Brand, c.Start()) \/\/ promoted method\n    fmt.Println(\"power:\", c.Power)  \/\/ promoted field\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Tata engine with 150 HP started\npower: 150<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q18. What is an anonymous struct in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An anonymous struct is a struct without a type name. You declare it and fill it in one step, and it exists only where you write it. So it is handy for short-lived data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ no \"type Person struct\" is needed\n    person := struct {\n        Name string\n        Age  int\n    }{\n        Name: \"Smita\",\n        Age:  25,\n    }\n\n    fmt.Println(person.Name, person.Age)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Smita 25<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You often use anonymous structs in these cases.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Temporary data inside one function.<\/li>\n\n\n\n<li>Shaping a JSON response quickly.<\/li>\n\n\n\n<li>Table-driven tests, where each test case is a small struct.<\/li>\n\n\n\n<li>One-time values where a named type would only add noise.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q19. What is the difference between new and init in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Neither one is a keyword. <code>new<\/code> is a built-in function, and <code>init<\/code> is a special function name. They have very different jobs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>new(T)<\/code> allocates memory for a type, sets it to the zero value and returns a pointer to it. You call it yourself whenever you need it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>init()<\/code> is a function that Go runs for you, before <code>main()<\/code> starts. It runs when its package is initialized.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>new<\/th><th>init<\/th><\/tr><\/thead><tbody><tr><td>Built-in function<\/td><td>Special function you write<\/td><\/tr><tr><td>You call it in your code<\/td><td>Go calls it automatically, you cannot call it<\/td><\/tr><tr><td>Takes a type, returns a pointer<\/td><td>Takes no arguments, returns nothing<\/td><\/tr><tr><td>Used for allocation<\/td><td>Used for package setup<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A file can have several <code>init<\/code> functions, and they run in the order they appear.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nvar config map&#91;string]string\n\n\/\/ init runs automatically before main\nfunc init() {\n    config = map&#91;string]string{\"env\": \"dev\"}\n    fmt.Println(\"init: config ready\")\n}\n\nfunc main() {\n    fmt.Println(\"main: env =\", config&#91;\"env\"])\n\n    p := new(int) \/\/ pointer to a zeroed int\n    fmt.Println(\"new int value:\", *p)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>init: config ready\nmain: env = dev\nnew int value: 0<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q20. What is the difference between a package and a module?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A package is a folder of Go files that share the same package name and are compiled together. A module is a versioned collection of related packages. So a module can hold many packages, and each package lives in one folder.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A module is defined by its <code>go.mod<\/code> file at the root. That file sets the module path, the Go version and the dependencies.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>module example.com\/shop\n\ngo 1.27\n\nrequire github.com\/google\/uuid v1.6.0<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Package<\/th><th>Module<\/th><\/tr><\/thead><tbody><tr><td>One folder of <code>.go<\/code> files<\/td><td>A tree of packages with a <code>go.mod<\/code> file<\/td><\/tr><tr><td>Imported by its path, like <code>example.com\/shop\/cart<\/code><\/td><td>Versioned and downloaded as one unit<\/td><\/tr><tr><td>Unit of code organisation<\/td><td>Unit of release and dependency management<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q21. How do you compile Go code on Windows and Linux?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use <code>go build<\/code> on both systems. It creates a binary for the current operating system, such as <code>app.exe<\/code> on Windows or <code>app<\/code> on Linux.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go build -o app .<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go also cross-compiles easily. You set two environment variables, <code>GOOS<\/code> for the operating system and <code>GOARCH<\/code> for the CPU type.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># On Linux or macOS, build a Windows binary\nGOOS=windows GOARCH=amd64 go build -o app.exe .<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code># On Windows PowerShell, build a Linux binary\n$env:GOOS=\"linux\"\n$env:GOARCH=\"amd64\"\ngo build -o app .<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can list every supported target with <code>go tool dist list<\/code>. If your code uses cgo, cross-compiling needs a C toolchain for the target, so many teams set <code>CGO_ENABLED=0<\/code> for simple static builds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q22. What is variable scope in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Variable scope is the part of the program where a variable can be used. Go uses block scope, so a variable declared inside <code>{ }<\/code> exists only inside those braces.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These are the main levels of scope.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Universe scope holds built-in names like <code>int<\/code>, <code>len<\/code> and <code>true<\/code>.<\/li>\n\n\n\n<li>Package scope covers variables declared outside any function. Every file in the package can use them.<\/li>\n\n\n\n<li>File scope applies to imports, which are visible only in the file that imports them.<\/li>\n\n\n\n<li>Function and block scope cover variables declared inside a function, an <code>if<\/code>, a <code>for<\/code> or a <code>switch<\/code>.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nvar appName = \"demo\" \/\/ package scope\n\nfunc main() {\n    count := 1 \/\/ function scope\n\n    if count &gt; 0 {\n        message := \"inside if\" \/\/ block scope\n        count := 99            \/\/ shadows the outer count\n        fmt.Println(message, count)\n    }\n\n    fmt.Println(appName, count) \/\/ outer count is unchanged\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>inside if 99\ndemo 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Watch out for shadowing, where an inner <code>:=<\/code> creates a new variable with the same name. Linters such as golangci-lint with the shadow check can warn you about it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Arrays, Slices, Maps and Strings<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Arrays, slices, maps and strings are the data types you use every day in Go. These Golang questions and answers cover how they work, how they differ and a few common patterns built on them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q23. What are slices in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A slice is a dynamic, flexible view over an underlying array. It does not store the data itself. Instead, it holds three things: a pointer to the array, a length and a capacity.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A slice can grow with the built-in <code>append<\/code> function.<\/li>\n\n\n\n<li>It is always backed by an array that Go manages for you.<\/li>\n\n\n\n<li>Its length and capacity are read with <code>len<\/code> and <code>cap<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small program that creates a slice and grows it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ A slice literal creates the backing array for you\n    nums := &#91;]int{1, 2, 3}\n\n    \/\/ append adds an element and returns the updated slice\n    nums = append(nums, 4)\n\n    fmt.Println(nums)\n    fmt.Println(\"length:\", len(nums))\n\n    \/\/ Slicing creates a new view over the same array\n    firstTwo := nums&#91;:2]\n    fmt.Println(firstTwo)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1 2 3 4]\nlength: 4\n&#91;1 2]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q24. 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 size, and that size is part of its type. So <code>[3]int<\/code> and <code>[4]int<\/code> are two different types. A slice has a dynamic size and works as a view into an underlying array.<\/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>Size<\/td><td>Fixed at compile time, for example <code>[3]int<\/code><\/td><td>Dynamic, can grow with <code>append<\/code>, for example <code>[]int<\/code><\/td><\/tr><tr><td>Declaration<\/td><td><code>var a [3]int<\/code><\/td><td><code>var s []int<\/code><\/td><\/tr><tr><td>Size in type<\/td><td>Yes, the length is part of the type<\/td><td>No, any length has the same type<\/td><\/tr><tr><td>Memory<\/td><td>Holds the elements directly<\/td><td>Holds a pointer, length and capacity<\/td><\/tr><tr><td>Passing to a function<\/td><td>The whole array is copied<\/td><td>The slice header is copied, but it shares the same array<\/td><\/tr><tr><td>Can grow?<\/td><td>No<\/td><td>Yes, with <code>append<\/code><\/td><\/tr><tr><td>Zero value<\/td><td>An array full of zero values<\/td><td><code>nil<\/code><\/td><\/tr><tr><td>Use in real code<\/td><td>Rare<\/td><td>Very common<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Go always passes arguments by value. When you pass a slice, Go copies only the small slice header. Because the copy points to the same array, changes to elements are visible to the caller. However, an <code>append<\/code> inside the function may create a new array, so the caller will not see the new length.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc changeArray(a &#91;3]int) {\n    a&#91;0] = 100 \/\/ changes only the local copy\n}\n\nfunc changeSlice(s &#91;]int) {\n    s&#91;0] = 100 \/\/ changes the shared backing array\n}\n\nfunc main() {\n    arr := &#91;3]int{1, 2, 3}\n    sl := &#91;]int{1, 2, 3}\n\n    changeArray(arr)\n    changeSlice(sl)\n\n    fmt.Println(\"array:\", arr)\n    fmt.Println(\"slice:\", sl)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>array: &#91;1 2 3]\nslice: &#91;100 2 3]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q25. What is the difference between len and cap?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>len<\/code> gives the number of elements currently in the slice. These are the elements you can read with an index. It is never negative and never larger than the capacity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>cap<\/code> gives the number of elements the backing array can hold, counted from the start of the slice. So it tells you how far the slice can grow before Go must allocate a bigger array.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Length means how many elements are actually in the slice.<\/li>\n\n\n\n<li>Capacity means how many elements fit before a reallocation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">When <code>append<\/code> goes past the capacity, Go allocates a new, larger array and copies the elements over. The exact growth size is an internal detail, so do not depend on it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ make creates a slice with length 3 and capacity 5\n    s := make(&#91;]int, 3, 5)\n    fmt.Println(len(s), cap(s))\n\n    \/\/ Two more elements still fit in the same array\n    s = append(s, 7, 8)\n    fmt.Println(len(s), cap(s))\n    fmt.Println(s)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3 5\n5 5\n&#91;0 0 0 7 8]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q26. What are maps in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A map stores key-value pairs. You look up a value by its key, and the lookup is fast on average. Keys must be a comparable type, such as <code>string<\/code>, <code>int<\/code> or a struct of comparable fields.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a key is missing, the map returns the zero value of the value type. So you use the &#8220;comma ok&#8221; form to check whether a key really exists. Also, the iteration order of a map is not fixed, so sort the keys when you need a stable order.<\/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    scores := map&#91;string]int{\n        \"a\": 1,\n        \"b\": 2,\n    }\n\n    \/\/ Check if a key exists with the comma ok idiom\n    v, ok := scores&#91;\"a\"]\n    fmt.Println(v, ok)\n\n    missing, ok := scores&#91;\"z\"]\n    fmt.Println(missing, ok)\n\n    \/\/ Sort the keys to get a predictable order\n    for _, key := range slices.Sorted(maps.Keys(scores)) {\n        fmt.Println(key, scores&#91;key])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 true\n0 false\na 1\nb 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q27. What is the difference between a nil slice and an empty slice?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A nil slice has no backing array, and it equals <code>nil<\/code>. You get one with <code>var s []int<\/code>. An empty slice has a backing array of size zero, so it is not <code>nil<\/code>. You get one with <code>s := []int{}<\/code> or <code>make([]int, 0)<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both have a length of 0, and both work with <code>len<\/code>, <code>append<\/code> and <code>range<\/code>. The difference shows up in <code>nil<\/code> checks and in JSON encoding. For example, a nil slice encodes as <code>null<\/code>, but 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 &#91;]int\n    emptySlice := &#91;]int{}\n\n    fmt.Println(len(nilSlice), nilSlice == nil)\n    fmt.Println(len(emptySlice), emptySlice == nil)\n\n    \/\/ JSON output differs between the two\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>0 true\n0 false\nnull &#91;]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q28. How do you define a map in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A map is a built-in type that stores key-value pairs. It is similar to a dictionary in Python or an object used as a lookup table in JavaScript. You write the type as <code>map[KeyType]ValueType<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A map declared with <code>var m map[string]int<\/code> is <code>nil<\/code>. Reading from a nil map is fine, but writing to it causes a panic. So create the map with <code>make<\/code> or a literal before you add values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    ages := make(map&#91;string]int)\n\n    ages&#91;\"Alice\"] = 30\n    ages&#91;\"Bob\"] = 25\n\n    \/\/ fmt prints maps with keys in sorted order\n    fmt.Println(ages)\n    fmt.Println(ages&#91;\"Bob\"])\n\n    delete(ages, \"Alice\")\n    fmt.Println(len(ages))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>map&#91;Alice:30 Bob:25]\n25\n1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the common map operations.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Operation<\/th><th>Syntax or example<\/th><\/tr><\/thead><tbody><tr><td>Declare<\/td><td><code>var m map[string]int<\/code><\/td><\/tr><tr><td>Initialize<\/td><td><code>m := make(map[string]int)<\/code><\/td><\/tr><tr><td>Literal<\/td><td><code>m := map[string]int{\"a\": 1}<\/code><\/td><\/tr><tr><td>Add or update a value<\/td><td><code>m[\"key\"] = value<\/code><\/td><\/tr><tr><td>Read a value<\/td><td><code>v := m[\"key\"]<\/code><\/td><\/tr><tr><td>Check existence<\/td><td><code>v, ok := m[\"key\"]<\/code><\/td><\/tr><tr><td>Delete a key<\/td><td><code>delete(m, \"key\")<\/code><\/td><\/tr><tr><td>Remove all keys<\/td><td><code>clear(m)<\/code><\/td><\/tr><tr><td>Loop<\/td><td><code>for k, v := range m { ... }<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q29. What is the difference between a rune and a string?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A string is an immutable sequence of bytes. It usually holds UTF-8 text. A rune is an alias for <code>int32<\/code>, and it holds one Unicode code point, which is roughly one character.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>len<\/code> on a string counts bytes, not characters. So for text with non-English letters, convert to <code>[]rune<\/code> or use <code>utf8.RuneCountInString<\/code> to count characters. Also, you cannot change a string in place. Instead, convert it to <code>[]rune<\/code>, change the runes, then convert it back.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>string<\/th><th>rune<\/th><\/tr><\/thead><tbody><tr><td>Type<\/td><td>Immutable sequence of bytes, usually UTF-8<\/td><td><code>int32<\/code>, one Unicode code point<\/td><\/tr><tr><td>Length<\/td><td><code>len(str)<\/code> gives bytes<\/td><td><code>len([]rune(str))<\/code> gives characters<\/td><\/tr><tr><td>Purpose<\/td><td>Full text<\/td><td>A single character<\/td><\/tr><tr><td>Can you change it?<\/td><td>No, strings are immutable<\/td><td>A <code>[]rune<\/code> slice can be changed<\/td><\/tr><tr><td>Useful for<\/td><td>Sentences, names and other text<\/td><td>Character processing and Unicode logic<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Task<\/th><th>Use<\/th><\/tr><\/thead><tbody><tr><td>Store or pass text<\/td><td><code>string<\/code><\/td><\/tr><tr><td>Work with single characters<\/td><td><code>rune<\/code><\/td><\/tr><tr><td>Count characters in text<\/td><td><code>utf8.RuneCountInString(str)<\/code> or <code>len([]rune(str))<\/code><\/td><\/tr><tr><td>Change characters, for example case<\/td><td><code>[]rune<\/code> or the <code>unicode<\/code> package<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    word := \"h\u00e9llo\"\n\n    fmt.Println(\"bytes:\", len(word))\n    fmt.Println(\"characters:\", utf8.RuneCountInString(word))\n\n    \/\/ range over a string gives runes, not bytes\n    for i, r := range word {\n        fmt.Printf(\"%d %c\\n\", i, r)\n    }\n\n    \/\/ Change a character through a &#91;]rune copy\n    runes := &#91;]rune(word)\n    runes&#91;0] = 'H'\n    fmt.Println(string(runes))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>bytes: 6\ncharacters: 5\n0 h\n1 \u00e9\n3 l\n4 l\n5 o\nH\u00e9llo<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q30. Why use a slice instead of an array?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Slices are the normal way to handle collections in Go. You reach for an array only when the size is fixed and known, for example a 16-byte key.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Flexibility.<\/strong> A slice can grow and shrink, but an array cannot.<\/li>\n\n\n\n<li><strong>Efficiency.<\/strong> Slices share the backing array, so slicing does not copy the data.<\/li>\n\n\n\n<li><strong>Simplicity.<\/strong> Built-in tools such as <code>append<\/code>, <code>copy<\/code> and the <code>slices<\/code> package work on slices.<\/li>\n\n\n\n<li><strong>Idiomatic Go.<\/strong> Most standard library functions take and return slices.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The old version of this answer talked about &#8220;call by reference&#8221;. However, Go has only call by value. When you pass an array, the whole array is copied. When you pass a slice, only its small header is copied, and it still points to the same data. If you need a function to change an array, pass a pointer to it, and that pointer is also copied by value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q31. What is the sliding window technique in data structures?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sliding window is a technique for arrays and strings. You keep a &#8220;window&#8221; over a range of elements. Then you move the window one step at a time instead of recomputing everything from scratch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, to find the largest sum of any 3 numbers in a row, you add the new element and subtract the element that left the window. So each step costs only a constant amount of work.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ maxSumOfK returns the largest sum of k consecutive numbers\nfunc maxSumOfK(nums &#91;]int, k int) int {\n    windowSum := 0\n    for i := 0; i &lt; k; i++ {\n        windowSum += nums&#91;i]\n    }\n    best := windowSum\n\n    \/\/ Slide the window: add the new element, drop the old one\n    for i := k; i &lt; len(nums); i++ {\n        windowSum += nums&#91;i] - nums&#91;i-k]\n        best = max(best, windowSum)\n    }\n    return best\n}\n\nfunc main() {\n    nums := &#91;]int{2, 1, 5, 1, 3, 2}\n    fmt.Println(maxSumOfK(nums, 3))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>9<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q32. Why use the sliding window technique?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It reduces time complexity because it avoids nested loops. A brute force solution often checks every subarray in O(n\u00b2) time. With a sliding window, you visit each element a small number of times, so the work drops to O(n).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are two main types.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Fixed size window.<\/strong> The window size stays the same. For example, find the maximum sum of a subarray of size k.<\/li>\n\n\n\n<li><strong>Variable size window.<\/strong> The window grows and shrinks based on a condition. For example, find the longest substring without repeating characters.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the variable size version for the longest substring problem.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ longestUnique returns the length of the longest substring\n\/\/ that has no repeated characters\nfunc longestUnique(s string) int {\n    lastSeen := make(map&#91;rune]int)\n    start, best := 0, 0\n    runes := &#91;]rune(s)\n\n    for end, ch := range runes {\n        \/\/ If ch is inside the window, move the start past it\n        if pos, ok := lastSeen&#91;ch]; ok &amp;&amp; pos &gt;= start {\n            start = pos + 1\n        }\n        lastSeen&#91;ch] = end\n        best = max(best, end-start+1)\n    }\n    return best\n}\n\nfunc main() {\n    fmt.Println(longestUnique(\"abcabcbb\"))\n    fmt.Println(longestUnique(\"bbbbb\"))\n    fmt.Println(longestUnique(\"pwwkew\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3\n1\n3<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Functions, Structs and Interfaces<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no classes, so functions, structs and interfaces do most of the design work. These Golang questions and answers show how they fit together, with small programs you can run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q33. What are interfaces in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An interface is a type that lists a set of method signatures. It describes behaviour, not data. Any type that has all those methods satisfies the interface automatically.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Implementation is implicit, so you never declare it.<\/li>\n\n\n\n<li>There is no <code>implements<\/code> keyword in Go.<\/li>\n\n\n\n<li>Small interfaces, such as <code>io.Reader<\/code> with one method, are common and easy to reuse.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Speaker is any type that can speak\ntype Speaker interface {\n    Speak() string\n}\n\ntype Dog struct{}\ntype Cat struct{}\n\n\/\/ Dog and Cat satisfy Speaker just by having a Speak method\nfunc (Dog) Speak() string { return \"Woof\" }\nfunc (Cat) Speak() string { return \"Meow\" }\n\nfunc main() {\n    animals := &#91;]Speaker{Dog{}, Cat{}}\n    for _, a := range animals {\n        fmt.Println(a.Speak())\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Woof\nMeow<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q34. What is an empty interface?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The empty interface, <code>interface{}<\/code>, has no methods. Every type has at least zero methods, so a value of any type can be stored in it. Since Go 1.18, <code>any<\/code> is a built-in alias for <code>interface{}<\/code>, and you should prefer <code>any<\/code> in new code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You lose compile-time type checks when you use <code>any<\/code>. So, to get the concrete value back, you need a type assertion or a type switch. Also, think about generics first when you only want code that works for many types.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    var anything any\n\n    anything = 42\n    fmt.Printf(\"%v %T\\n\", anything, anything)\n\n    anything = \"hello\"\n    fmt.Printf(\"%v %T\\n\", anything, anything)\n\n    anything = &#91;]string{\"a\", \"b\"}\n    fmt.Printf(\"%v %T\\n\", anything, anything)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>42 int\nhello string\n&#91;a b] &#91;]string<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q35. What is type assertion?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A type assertion pulls the concrete value out of an interface. You write <code>i.(T)<\/code>, where <code>T<\/code> is the type you expect. If the value is not of type <code>T<\/code>, the single-value form panics.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So use the safe &#8220;comma ok&#8221; form when you are not sure. It returns the value and a boolean. When the check fails, you get the zero value of <code>T<\/code> and <code>false<\/code>, with no panic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    var i any = \"hello\"\n\n    \/\/ Single-value form: panics if i is not a string\n    s := i.(string)\n    fmt.Println(s)\n\n    \/\/ Safe form: ok is false instead of a panic\n    n, ok := i.(int)\n    fmt.Println(n, ok)\n\n    text, ok := i.(string)\n    fmt.Println(text, ok)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>hello\n0 false\nhello true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q36. What is a struct?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A struct groups related fields into one type. For example, a <code>User<\/code> can hold a name, an age and an email together. Structs are value types, so assigning one to another variable copies all its fields.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can attach methods to a struct. Then you can pass a pointer to it when a function needs to change the original.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype User struct {\n    Name  string\n    Age   int\n    Email string\n}\n\nfunc main() {\n    u := User{Name: \"Asha\", Age: 28}\n    u.Email = \"asha@example.com\"\n    fmt.Printf(\"%+v\\n\", u)\n\n    \/\/ A pointer lets you change the original struct\n    p := &amp;u\n    p.Age = 29\n    fmt.Println(u.Age)\n\n    \/\/ Fields you do not set get their zero values\n    var empty User\n    fmt.Printf(\"%+v\\n\", empty)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{Name:Asha Age:28 Email:asha@example.com}\n29\n{Name: Age:0 Email:}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q37. Does Go support inheritance?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No, Go does not support classical inheritance. There are no classes, no <code>extends<\/code> keyword and no type hierarchy. Instead, Go gives you two tools.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Composition, where a struct holds other types as fields.<\/li>\n\n\n\n<li>Embedding, where a struct includes another type without a field name, so its fields and methods are promoted.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For shared behaviour across different types, you use interfaces. Here, <code>Car<\/code> embeds <code>Engine<\/code> and can call <code>Start<\/code> directly.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Engine struct {\n    Power int\n}\n\nfunc (e Engine) Start() string {\n    return fmt.Sprintf(\"engine with %d HP started\", e.Power)\n}\n\n\/\/ Car embeds Engine, so Engine's fields and methods are promoted\ntype Car struct {\n    Engine\n    Model string\n}\n\nfunc main() {\n    c := Car{Engine: Engine{Power: 150}, Model: \"Sedan\"}\n    fmt.Println(c.Model)\n    fmt.Println(c.Power)   \/\/ promoted field\n    fmt.Println(c.Start()) \/\/ promoted method\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Sedan\n150\nengine with 150 HP started<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q38. What is embedding in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding lets one struct include another type directly, without giving it a field name. The fields and methods of the embedded type are then promoted. So you can call them on the outer struct as if they were its own.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding is composition, not inheritance. A <code>Car<\/code> that embeds <code>Engine<\/code> is not an <code>Engine<\/code>, and you cannot pass a <code>Car<\/code> where an <code>Engine<\/code> is expected. However, if the promoted methods satisfy an interface, the outer struct satisfies that interface too.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can also embed interfaces inside interfaces. For example, <code>io.ReadWriter<\/code> embeds <code>io.Reader<\/code> and <code>io.Writer<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Interface embedding in the standard library\ntype ReadWriter interface {\n    Reader\n    Writer\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q39. What is defer?<\/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. It runs even if the function returns early or panics. So it is the standard way to clean up resources.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Closing files and network connections.<\/li>\n\n\n\n<li>Releasing a mutex with <code>mu.Unlock()<\/code>.<\/li>\n\n\n\n<li>Other cleanup tasks, such as stopping a timer.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Deferred calls run in last in, first out order. Also, the arguments of a deferred call are evaluated right away, not when the call finally runs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(\"start\")\n\n    for i := 1; i &lt;= 3; i++ {\n        defer fmt.Println(\"deferred\", i)\n    }\n\n    x := 10\n    \/\/ x is evaluated now, so this prints 10\n    defer fmt.Println(\"x at defer time:\", x)\n    x = 20\n    fmt.Println(\"x now:\", x)\n\n    fmt.Println(\"end\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>start\nx now: 20\nend\nx at defer time: 10\ndeferred 3\ndeferred 2\ndeferred 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q40. How do you find out which type of value is stored in an interface, for example int or string?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A single type assertion works when you expect one type. But when the value could be one of many types, a type switch is cleaner. It looks like a normal <code>switch<\/code>, but it uses <code>i.(type)<\/code>, and inside each case the variable already has that concrete type.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"reflect\"\n)\n\nfunc describe(i any) string {\n    switch v := i.(type) {\n    case int:\n        return fmt.Sprintf(\"int with value %d\", v)\n    case string:\n        return fmt.Sprintf(\"string of length %d\", len(v))\n    case float64:\n        return fmt.Sprintf(\"float64 with value %.2f\", v)\n    case nil:\n        return \"nil value\"\n    default:\n        \/\/ %T prints the dynamic type of any value\n        return fmt.Sprintf(\"other type: %T\", v)\n    }\n}\n\nfunc main() {\n    values := &#91;]any{42, \"hello\", 3.14, nil, true}\n    for _, v := range values {\n        fmt.Println(describe(v))\n    }\n\n    \/\/ reflect.TypeOf is handy for logging and debugging\n    fmt.Println(reflect.TypeOf(3.14))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>int with value 42\nstring of length 5\nfloat64 with value 3.14\nnil value\nother type: bool\nfloat64<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a quick comparison of the three ways.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Method<\/th><th>Use case<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Type assertion<\/td><td>Extract one known type<\/td><td><code>v, ok := i.(string)<\/code><\/td><\/tr><tr><td>Type switch<\/td><td>Handle many types cleanly<\/td><td><code>switch v := i.(type) { ... }<\/code><\/td><\/tr><tr><td><code>%T<\/code> or <code>reflect.TypeOf<\/code><\/td><td>Logging or generic inspection<\/td><td><code>fmt.Printf(\"%T\", i)<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q41. What is a wrapper function?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A wrapper function wraps another function to add extra behaviour before, after or around it. You do not change the original code. In Go, a wrapper usually takes a function and returns a new function with the same signature. This is the decorator pattern.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no wrapper classes like Java. Instead, you use functions, closures and sometimes structs that embed another type.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Code reuse.<\/strong> You write logging, timing or retries once and apply them to many functions.<\/li>\n\n\n\n<li><strong>Separation of concerns.<\/strong> Core logic stays clean, and the extra behaviour lives in the wrapper.<\/li>\n\n\n\n<li><strong>Middleware.<\/strong> HTTP middleware in <code>net\/http<\/code>, Gin or Fiber is a wrapper around a handler.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ withLogging returns a new function that logs around fn\nfunc withLogging(name string, fn func(int, int) int) func(int, int) int {\n    return func(a, b int) int {\n        fmt.Printf(\"calling %s(%d, %d)\\n\", name, a, b)\n        result := fn(a, b)\n        fmt.Printf(\"%s returned %d\\n\", name, result)\n        return result\n    }\n}\n\nfunc main() {\n    add := withLogging(\"add\", func(a, b int) int { return a + b })\n    total := add(2, 3)\n    fmt.Println(\"total:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>calling add(2, 3)\nadd returned 5\ntotal: 5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the same idea as HTTP middleware with the standard library.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func logRequests(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        log.Println(r.Method, r.URL.Path)\n        next.ServeHTTP(w, r) \/\/ call the wrapped handler\n    })\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q42. What is a callback function?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A callback is a function you pass as an argument to another function. The receiving function calls it later, usually after it finishes some work. In other words, you tell the function, &#8220;when you are done, call this for me&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go functions are first-class values, so callbacks are easy. A callback runs on the same goroutine unless you start a new one. For async work in Go, you usually use goroutines and channels rather than chains of callbacks.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Flexibility.<\/strong> Behaviour changes based on which callback you pass.<\/li>\n\n\n\n<li><strong>Separation of concerns.<\/strong> The processing logic and the &#8220;what to do next&#8221; step stay apart.<\/li>\n\n\n\n<li><strong>Common uses.<\/strong> You see them in <code>sort.Slice<\/code>, <code>strings.Map<\/code> and <code>http.HandleFunc<\/code>.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ processData takes another function as an argument\nfunc processData(data string, callback func(string)) {\n    fmt.Println(\"Processing:\", data)\n    callback(data) \/\/ call the callback after processing\n}\n\nfunc printResult(result string) {\n    fmt.Println(\"Processed result:\", result)\n}\n\nfunc main() {\n    processData(\"Hello Golang\", printResult)\n\n    \/\/ An anonymous function works as a callback too\n    processData(\"go\", func(s string) {\n        fmt.Println(\"Upper:\", strings.ToUpper(s))\n    })\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Processing: Hello Golang\nProcessed result: Hello Golang\nProcessing: go\nUpper: GO<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q43. What is polymorphism, and how do you achieve it in Go using interfaces?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Polymorphism means different types can be used through the same interface, and each type gives its own behaviour. So the same method call can do different things depending on the value behind it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no classes, but interfaces give you polymorphism. If a type has all the methods of an interface, it satisfies that interface implicitly.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>There is no inheritance, only interfaces and methods on types.<\/li>\n\n\n\n<li>Implementation is implicit, with no <code>implements<\/code> keyword.<\/li>\n\n\n\n<li>The method that runs depends on the dynamic type stored in the interface at runtime.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\ntype Shape interface {\n    Area() float64\n}\n\ntype Rectangle struct{ Width, Height float64 }\ntype Circle struct{ Radius float64 }\n\nfunc (r Rectangle) Area() float64 { return r.Width * r.Height }\nfunc (c Circle) Area() float64    { return math.Pi * c.Radius * c.Radius }\n\nfunc main() {\n    shapes := &#91;]Shape{Rectangle{3, 4}, Circle{2}}\n\n    \/\/ The same call runs a different Area method for each type\n    for _, s := range shapes {\n        fmt.Printf(\"%T area: %.2f\\n\", s, s.Area())\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main.Rectangle area: 12.00\nmain.Circle area: 12.57<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q44. What is a closure function in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A closure is a function that captures variables from the scope where it was defined. It keeps those variables alive even after the outer function has returned. You can think of it as a function with a memory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the example, the inner function remembers <code>count<\/code>. Each call to <code>counter()<\/code> creates a new <code>count<\/code>, so <code>c1<\/code> and <code>c2<\/code> do not share state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc counter() func() int {\n    count := 0\n    return func() int {\n        count++ \/\/ count lives on inside the closure\n        return count\n    }\n}\n\nfunc main() {\n    c1 := counter()\n    fmt.Println(c1())\n    fmt.Println(c1())\n    fmt.Println(c1())\n\n    c2 := counter() \/\/ separate memory\n    fmt.Println(c2())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\n3\n1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Closures and loops were a classic trap in old Go. Since Go 1.22, each loop iteration gets its own copy of the loop variable. This means a closure created inside a <code>for<\/code> loop now captures the value for that iteration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q45. What are generics in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generics let you write functions and data types that work with many types while keeping type safety. Before Go 1.18, developers used <code>interface{}<\/code> for this, but they lost compile-time checks and needed type assertions. Generics arrived in Go 1.18, released in March 2022.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Type parameters go in square brackets, for example <code>[T any]<\/code>.<\/li>\n\n\n\n<li>Constraints limit the allowed types, for example <code>int | float64<\/code> or <code>cmp.Ordered<\/code>.<\/li>\n\n\n\n<li>The <code>~<\/code> sign, as in <code>~int<\/code>, also allows types whose underlying type is <code>int<\/code>.<\/li>\n\n\n\n<li>Generics give you code reuse with full type safety.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Number allows any type whose underlying type is int or float64\ntype Number interface {\n    ~int | ~float64\n}\n\nfunc Sum&#91;T Number](nums &#91;]T) T {\n    var total T\n    for _, n := range nums {\n        total += n\n    }\n    return total\n}\n\n\/\/ Filter keeps the items for which keep returns true\nfunc Filter&#91;T any](items &#91;]T, keep func(T) bool) &#91;]T {\n    var result &#91;]T\n    for _, item := range items {\n        if keep(item) {\n            result = append(result, item)\n        }\n    }\n    return result\n}\n\nfunc main() {\n    fmt.Println(Sum(&#91;]int{1, 2, 3}))\n    fmt.Println(Sum(&#91;]float64{1.5, 2.5}))\n\n    evens := Filter(&#91;]int{1, 2, 3, 4, 5, 6}, func(n int) bool { return n%2 == 0 })\n    fmt.Println(evens)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>6\n4\n&#91;2 4 6]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q46. What is composition in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Composition means building a type out of other types. In Go, you embed structs or interfaces inside a struct, or hold them as named fields. This gives you code reuse and polymorphic behaviour without inheritance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A related interview question is &#8220;Why use an empty struct in Go?&#8221;. The empty struct, <code>struct{}<\/code>, takes zero bytes of memory. So it is ideal when only presence or a signal matters, not the data.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>As a map value to build a set, for example <code>map[string]struct{}<\/code>.<\/li>\n\n\n\n<li>Inside channels as a signal, for example <code>chan struct{}<\/code> to tell goroutines to stop.<\/li>\n\n\n\n<li>As a placeholder type that only carries methods.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"unsafe\"\n)\n\nfunc main() {\n    fmt.Println(\"size:\", unsafe.Sizeof(struct{}{}))\n\n    \/\/ A set of strings, using struct{} as a zero-size value\n    seen := map&#91;string]struct{}{}\n    for _, lang := range &#91;]string{\"go\", \"java\", \"go\"} {\n        seen&#91;lang] = struct{}{}\n    }\n    fmt.Println(\"unique:\", len(seen))\n\n    _, ok := seen&#91;\"go\"]\n    fmt.Println(\"has go:\", ok)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>size: 0\nunique: 2\nhas go: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The old post also had a coding puzzle here. It asks you to find the letters common to all words, so <code>[\"sumita\", \"amit\", \"mahesh\"]<\/code> gives <code>[a m]<\/code>. The program counts letters in the first word, then keeps the smallest count seen in every other word. Finally, it sorts the result so the output is stable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc commonChars(words &#91;]string) &#91;]string {\n    if len(words) == 0 {\n        return &#91;]string{}\n    }\n\n    \/\/ Count letters in the first word\n    common := make(map&#91;rune]int)\n    for _, ch := range words&#91;0] {\n        common&#91;ch]++\n    }\n\n    \/\/ Keep the minimum count across the other words\n    for _, word := range words&#91;1:] {\n        counts := make(map&#91;rune]int)\n        for _, ch := range word {\n            counts&#91;ch]++\n        }\n        for ch, c := range common {\n            common&#91;ch] = min(c, counts&#91;ch])\n        }\n    }\n\n    \/\/ Collect the letters, then sort for a stable order\n    var result &#91;]string\n    for ch, count := range common {\n        for i := 0; i &lt; count; i++ {\n            result = append(result, string(ch))\n        }\n    }\n    sort.Strings(result)\n    return result\n}\n\nfunc main() {\n    words := &#91;]string{\"sumita\", \"amit\", \"mahesh\"}\n    fmt.Println(commonChars(words))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;a m]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q47. What is reflection in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reflection lets a program inspect and change values whose types are only known at runtime. Go provides it through the <code>reflect<\/code> package. Normally, types are known at compile time, but sometimes you need more flexibility.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Inspecting an unknown type, as JSON encoders and ORMs such as GORM do.<\/li>\n\n\n\n<li>Reading struct fields, struct tags and methods dynamically.<\/li>\n\n\n\n<li>Writing general tools for logging, validation or data mapping.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The key concepts are listed below.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><code>reflect.TypeOf(x)<\/code> returns the type of a value.<\/li>\n\n\n\n<li><code>reflect.ValueOf(x)<\/code> returns the value itself, wrapped in a <code>reflect.Value<\/code>.<\/li>\n\n\n\n<li><code>Kind<\/code> is the underlying category, such as int, string, slice or struct.<\/li>\n\n\n\n<li><code>Set<\/code> methods change a value, but only if it is settable. That means you must reflect on a pointer and call <code>Elem<\/code>, and struct fields must be exported.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Reflection is slower and less safe than normal code. So prefer interfaces or generics when they can do the job.<\/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\n    Age  int\n}\n\nfunc main() {\n    u := User{Name: \"Asha\", Age: 30}\n\n    t := reflect.TypeOf(u)\n    fmt.Println(t, t.Kind())\n\n    \/\/ Loop over the struct fields\n    v := reflect.ValueOf(u)\n    for i := 0; i &lt; t.NumField(); i++ {\n        fmt.Printf(\"%s %s = %v\\n\", t.Field(i).Name, t.Field(i).Type, v.Field(i))\n    }\n\n    \/\/ To change a field, reflect on a pointer and use Elem\n    pv := reflect.ValueOf(&amp;u).Elem()\n    pv.FieldByName(\"Age\").SetInt(31)\n    fmt.Println(u.Age)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main.User struct\nName string = Asha\nAge int = 30\n31<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q48. What is dependency injection in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dependency injection (DI) is a design pattern where a type receives its dependencies from outside instead of creating them itself. In short, do not build dependencies inside a struct or function, pass them in.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, you usually do this with plain constructor functions and small interfaces. No framework is needed. Because the struct depends on an interface, you can pass a real implementation in production and a fake one in tests. This makes your code loosely coupled, easier to test and easier to maintain.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Notifier is the dependency, described as an interface\ntype Notifier interface {\n    Send(to, msg string) error\n}\n\ntype EmailNotifier struct{}\n\nfunc (EmailNotifier) Send(to, msg string) error {\n    fmt.Printf(\"email to %s: %s\\n\", to, msg)\n    return nil\n}\n\n\/\/ FakeNotifier records messages, which is useful in tests\ntype FakeNotifier struct {\n    sent &#91;]string\n}\n\nfunc (f *FakeNotifier) Send(to, msg string) error {\n    f.sent = append(f.sent, to+\": \"+msg)\n    return nil\n}\n\ntype OrderService struct {\n    notifier Notifier\n}\n\n\/\/ NewOrderService receives its dependency from outside\nfunc NewOrderService(n Notifier) *OrderService {\n    return &amp;OrderService{notifier: n}\n}\n\nfunc (s *OrderService) PlaceOrder(user string) error {\n    return s.notifier.Send(user, \"your order is placed\")\n}\n\nfunc main() {\n    real := NewOrderService(EmailNotifier{})\n    real.PlaceOrder(\"asha@example.com\")\n\n    fake := &amp;FakeNotifier{}\n    test := NewOrderService(fake)\n    test.PlaceOrder(\"test-user\")\n    fmt.Println(\"fake sent:\", fake.sent)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>email to asha@example.com: your order is placed\nfake sent: &#91;test-user: your order is placed]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Error Handling<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go treats errors as normal values that functions return, not as exceptions. These Golang questions and answers show how to create, wrap, check and recover from errors the Go way.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q49. What are panic and recover in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>panic<\/code> stops the normal flow of a goroutine. When a panic happens, Go runs the deferred functions of the current function, then of its callers, one by one. If nothing stops it, the program crashes and prints a stack trace.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>recover<\/code> is a built-in function that stops a panic. However, it only works when you call it directly inside a deferred function. Outside a deferred function, <code>recover<\/code> simply returns <code>nil<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ safeDivide turns a panic into a normal error value\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    fmt.Println(\"program keeps running\")\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\nprogram keeps running<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>panic<\/code> only for real bugs or states that should never happen. For expected problems, such as a missing file or bad user input, return an <code>error<\/code> instead. Also, <code>recover<\/code> only catches panics in its own goroutine, so a panic in another goroutine still crashes the program.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q50. What are error wrapping and unwrapping in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.13, you can wrap an error to add context while keeping the original cause. Then the caller can still check what went wrong underneath. This gives you messages that show both where and why an error happened.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To wrap an error, use <code>fmt.Errorf<\/code> with the <code>%w<\/code> verb. To look inside the chain, use the <code>errors<\/code> package.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>errors.Is(err, target)<\/code> checks if <code>err<\/code> or any error it wraps equals <code>target<\/code>.<\/li>\n\n\n\n<li><code>errors.As(err, &amp;target)<\/code> finds the first error in the chain of a given type and stores it in <code>target<\/code>.<\/li>\n\n\n\n<li><code>errors.Unwrap(err)<\/code> returns the next error in the chain, one layer down.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"os\"\n)\n\nvar ErrNotFound = errors.New(\"record not found\")\n\nfunc findUser(id int) error {\n    if id == 0 {\n        return ErrNotFound\n    }\n    return nil\n}\n\nfunc getUser(id int) error {\n    if err := findUser(id); err != nil {\n        \/\/ wrap the original error with more context\n        return fmt.Errorf(\"getUser failed: %w\", err)\n    }\n    return nil\n}\n\nfunc main() {\n    err := getUser(0)\n    fmt.Println(\"error:\", err)\n\n    \/\/ errors.Is looks through every wrapped layer\n    if errors.Is(err, ErrNotFound) {\n        fmt.Println(\"user not found\")\n    }\n\n    \/\/ errors.Unwrap removes one layer\n    fmt.Println(\"cause:\", errors.Unwrap(err))\n\n    \/\/ errors.As finds an error of a specific type\n    _, openErr := os.Open(\"missing.txt\")\n    wrapped := fmt.Errorf(\"load config: %w\", openErr)\n    var pathErr *os.PathError\n    if errors.As(wrapped, &amp;pathErr) {\n        fmt.Println(\"path error on file:\", pathErr.Path)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>error: getUser failed: record not found\nuser not found\ncause: record not found\npath error on file: missing.txt<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Always prefer <code>errors.Is<\/code> over <code>err == ErrNotFound<\/code>, because <code>==<\/code> fails once the error is wrapped. Also, since Go 1.20 you can wrap several errors at once with <code>errors.Join<\/code> or with more than one <code>%w<\/code> in <code>fmt.Errorf<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Action<\/th><th>How<\/th><\/tr><\/thead><tbody><tr><td>Wrap (add context)<\/td><td><code>fmt.Errorf(\"doing X: %w\", err)<\/code><\/td><\/tr><tr><td>Check for a specific error value<\/td><td><code>errors.Is(err, ErrNotFound)<\/code><\/td><\/tr><tr><td>Get an error of a specific type<\/td><td><code>errors.As(err, &amp;pathErr)<\/code><\/td><\/tr><tr><td>Remove one layer<\/td><td><code>errors.Unwrap(err)<\/code><\/td><\/tr><tr><td>Combine several errors<\/td><td><code>errors.Join(err1, err2)<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q51. What are the common ways to handle errors in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no try and catch. Instead, a function returns an <code>error<\/code> as its last value, and you check it right away with <code>if err != nil<\/code>. Here are the patterns you use most often.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, return the error to the caller. This is the simplest choice when the current function cannot fix the problem.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, wrap the error with context, so the final message tells the full story. Interviewers like this pattern because it shows you care about debugging.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>f, err := os.Open(path)\nif err != nil {\n    return fmt.Errorf(\"failed to open file %q: %w\", path, err)\n}\ndefer f.Close()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, use sentinel errors or custom error types for business rules. A sentinel error is a package-level variable that callers can check with <code>errors.Is<\/code>. A custom type is a struct with an <code>Error() string<\/code> method, and it can carry extra fields.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ sentinel error for a known business case\nvar ErrUserNotFound = errors.New(\"user not found\")\n\n\/\/ custom error type with extra details\ntype ValidationError struct {\n    Field string\n}\n\nfunc (v *ValidationError) Error() string {\n    return \"invalid field: \" + v.Field\n}\n\nfunc createUser(name string) error {\n    if name == \"\" {\n        return &amp;ValidationError{Field: \"name\"}\n    }\n    return nil\n}\n\nfunc findUser(id int) error {\n    if id != 1 {\n        return fmt.Errorf(\"findUser %d: %w\", id, ErrUserNotFound)\n    }\n    return nil\n}\n\nfunc main() {\n    if err := findUser(7); errors.Is(err, ErrUserNotFound) {\n        fmt.Println(\"handled:\", err)\n    }\n\n    var vErr *ValidationError\n    if err := createUser(\"\"); errors.As(err, &amp;vErr) {\n        fmt.Println(\"bad field:\", vErr.Field)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>handled: findUser 7: user not found\nbad field: name<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When does a panic happen? Go raises a runtime panic in situations like these.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Indexing a slice, array or string out of range.<\/li>\n\n\n\n<li>Dereferencing a <code>nil<\/code> pointer.<\/li>\n\n\n\n<li>Integer division by zero. Floating-point division by zero does not panic, it gives <code>+Inf<\/code> or <code>NaN<\/code>.<\/li>\n\n\n\n<li>Writing to a <code>nil<\/code> map.<\/li>\n\n\n\n<li>Sending on a closed channel, or closing a channel twice.<\/li>\n\n\n\n<li>A failed type assertion without the <code>, ok<\/code> form.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">However, calling <code>Close<\/code> on a <code>nil<\/code> <code>*os.File<\/code> does not panic. It returns the error <code>os.ErrInvalid<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Panic<\/th><th>Error<\/th><\/tr><\/thead><tbody><tr><td>Stops the program unless recovered<\/td><td>Returned and handled by the caller<\/td><\/tr><tr><td>For bugs and impossible states<\/td><td>For expected failures<\/td><\/tr><tr><td>Rare in normal code<\/td><td>The standard Go approach<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">To stop a panic, call <code>recover()<\/code> inside a deferred function, as shown in the panic and recover answer above. Servers often do this in middleware, so one bad request does not crash the whole service.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Goroutines and Concurrency<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Concurrency is one of the main reasons people pick Go. So these Golang questions and answers cover goroutines, channels, select, mutexes, the scheduler and the common bugs you will meet in interviews and real projects.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q52. What are goroutines?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A goroutine is a function that runs concurrently with other code. The Go runtime manages it, not the operating system. You start one by writing the <code>go<\/code> keyword before a function call.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Goroutines are very cheap. Each one starts with a small stack of a few kilobytes, and the stack grows when needed. So a program can run thousands or even millions of them. They are not &#8220;faster&#8221; than OS threads at running code, but they are much cheaper to create and to switch between.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Very low memory use per goroutine<\/li>\n\n\n\n<li>Cheap to create and to switch<\/li>\n\n\n\n<li>Many goroutines share a small number of OS threads<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small program. Each goroutine writes its result into its own slot, so the output order is always the same.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc square(n int) int {\n    return n * n\n}\n\nfunc main() {\n    numbers := &#91;]int{1, 2, 3, 4}\n    results := make(&#91;]int, len(numbers)) \/\/ one slot per goroutine\n\n    var wg sync.WaitGroup\n    for i, n := range numbers {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            results&#91;i] = square(n) \/\/ each goroutine writes only its own slot\n        }()\n    }\n    wg.Wait() \/\/ wait until every goroutine has finished\n\n    fmt.Println(results)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1 4 9 16]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.22 each loop iteration gets its own <code>i<\/code> and <code>n<\/code>, so the closure above is safe without copying the variables.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q53. What is a channel in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A channel is a typed pipe that lets goroutines talk to each other. One goroutine sends a value into the channel, and another goroutine receives it. This follows the Go idea &#8220;share memory by communicating&#8221; instead of sharing variables and locking them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You create a channel with <code>make<\/code>. Then you send with <code>ch &lt;- value<\/code> and receive with <code>value := &lt;-ch<\/code>. On an unbuffered channel the send and the receive wait for each other, so a channel also synchronises goroutines.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Type<\/th><th>Description<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Unbuffered<\/td><td>A send waits until a receiver takes the value<\/td><td><code>make(chan int)<\/code><\/td><\/tr><tr><td>Buffered<\/td><td>A send waits only when the buffer is full<\/td><td><code>make(chan int, 5)<\/code><\/td><\/tr><tr><td>Receive-only<\/td><td>You can only read from it<\/td><td><code>var ch &lt;-chan int<\/code><\/td><\/tr><tr><td>Send-only<\/td><td>You can only write to it<\/td><td><code>var ch chan&lt;- int<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a basic example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    ch := make(chan int) \/\/ unbuffered channel of int\n\n    go func() {\n        ch &lt;- 10 \/\/ send blocks until main receives\n    }()\n\n    value := &lt;-ch \/\/ receive waits for the send\n    fmt.Println(\"received:\", value)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>received: 10<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Channels give you safe communication, built-in synchronisation and fewer shared-memory bugs. When the sender has no more data, it can call <code>close(ch)<\/code>, and receivers can then use <code>for v := range ch<\/code> to read until the channel is empty.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q54. What is the difference between buffered and unbuffered channels?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An unbuffered channel has capacity 0. Every send blocks until another goroutine receives, and a receive blocks until another goroutine sends. So it works like a direct hand-off between two goroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A buffered channel has a capacity greater than 0. A send only blocks when the buffer is full, and a receive only blocks when the buffer is empty. This means it acts like a small queue.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Unbuffered channel<\/th><th>Buffered channel<\/th><\/tr><\/thead><tbody><tr><td>Created with<\/td><td><code>make(chan T)<\/code><\/td><td><code>make(chan T, n)<\/code> with n &gt; 0<\/td><\/tr><tr><td>Capacity<\/td><td>0<\/td><td>n<\/td><\/tr><tr><td>Send blocks<\/td><td>Until a receiver takes the value<\/td><td>Only when the buffer is full<\/td><\/tr><tr><td>Receive blocks<\/td><td>Until a sender sends<\/td><td>Only when the buffer is empty<\/td><\/tr><tr><td>Behaviour<\/td><td>Direct hand-off, strict sync<\/td><td>Queue, smooths out bursts<\/td><\/tr><tr><td>Common use<\/td><td>Signalling and coordination<\/td><td>Worker pools, pipelines, rate limiting<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a buffered channel in action. No other goroutine is needed because the buffer holds the values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    ch := make(chan int, 3) \/\/ buffer can hold 3 values\n\n    ch &lt;- 1 \/\/ does not block\n    ch &lt;- 2\n    ch &lt;- 3 \/\/ buffer is now full\n    fmt.Println(\"len:\", len(ch), \"cap:\", cap(ch))\n\n    fmt.Println(&lt;-ch) \/\/ takes 1 and frees one slot\n    ch &lt;- 4           \/\/ this send succeeds right away\n\n    fmt.Println(&lt;-ch, &lt;-ch, &lt;-ch)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>len: 3 cap: 3\n1\n2 3 4<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you wrote <code>ch &lt;- 4<\/code> while the buffer was full and nobody was receiving, the program would block forever and Go would report a deadlock.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q55. What is the difference between concurrency and parallelism?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Concurrency means dealing with many tasks at once. The tasks can take turns on one CPU core, so their work is interleaved. Parallelism means running many tasks at exactly the same time on several CPU cores.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As Rob Pike says, concurrency is about structure, and parallelism is about execution. Goroutines give you concurrency. Then, if your machine has more than one core, the Go runtime runs goroutines in parallel.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Point<\/th><th>Concurrency<\/th><th>Parallelism<\/th><\/tr><\/thead><tbody><tr><td>Meaning<\/td><td>Managing many tasks, switching between them<\/td><td>Running many tasks at the same instant<\/td><\/tr><tr><td>Goal<\/td><td>Structure and responsiveness<\/td><td>Speed<\/td><\/tr><tr><td>Needs many cores<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Analogy<\/td><td>One chef cooking many dishes by switching<\/td><td>Several chefs cooking at once<\/td><\/tr><tr><td>In Go<\/td><td>Goroutines and channels<\/td><td>Goroutines on many cores, controlled by <code>GOMAXPROCS<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q56. What is GOMAXPROCS?<\/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. In the GMP model it is the number of P (processors). So it is the limit on how many goroutines truly run in parallel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default it equals the number of CPU cores the program can use. Since Go 1.25 the default also respects container CPU limits (cgroups) on Linux and updates if the limit changes. You rarely need to set it yourself. You can read or change it with the <code>runtime<\/code> package or the <code>GOMAXPROCS<\/code> environment variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>current := runtime.GOMAXPROCS(0) \/\/ 0 means \"just read the value\"\nfmt.Println(\"GOMAXPROCS:\", current)\n\nruntime.GOMAXPROCS(4) \/\/ allow at most 4 threads to run Go code at once<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Threads that are blocked in system calls do not count toward this limit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q57. What is a mutex, and why do you use it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A mutex (mutual exclusion lock) makes sure only one goroutine at a time runs a piece of code. That piece of code is called the critical section. Go provides it as <code>sync.Mutex<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You need it because goroutines run concurrently. If many of them read and write the same variable without control, you get race conditions, broken data and bugs that are hard to repeat. A mutex prevents this by making the goroutines take turns.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>API<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td><code>mu.Lock()<\/code><\/td><td>Takes the lock, waits if another goroutine holds it<\/td><\/tr><tr><td>Release call on <code>mu<\/code><\/td><td>Gives the lock back so the next goroutine can enter<\/td><\/tr><tr><td><code>mu.TryLock()<\/code><\/td><td>Tries to take the lock without waiting (Go 1.18+), rarely needed<\/td><\/tr><tr><td><code>sync.RWMutex<\/code><\/td><td>A separate type that allows many readers or one writer<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a counter that 1000 goroutines update safely.<\/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 (\n        mu      sync.Mutex\n        counter int\n        wg      sync.WaitGroup\n    )\n\n    for range 1000 {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            mu.Lock()\n            counter++ \/\/ only one goroutine runs this line at a time\n            mu.Unlock()\n        }()\n    }\n    wg.Wait()\n\n    fmt.Println(\"counter:\", counter)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>counter: 1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Without the mutex the final value could be less than 1000, because <code>counter++<\/code> is a read, an add and a write, not one atomic step.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q58. What is a race condition?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A race condition (a data race) happens when two or more goroutines access the same memory at the same time, and at least one of them writes. The result then depends on timing, so the program may give wrong or different results on each run. In Go, a data race is a real bug, not just a style issue.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a racy counter. Two goroutines update <code>count<\/code> with no protection.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var count int\n\nfunc increment(wg *sync.WaitGroup) {\n    defer wg.Done()\n    for range 1000 {\n        count++ \/\/ not safe: read, add, write can interleave\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can find races with the built-in race detector. Just add the <code>-race<\/code> flag.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go run -race main.go\ngo test -race .\/...<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To fix a race, protect the shared data with a <code>sync.Mutex<\/code>, use the <code>sync\/atomic<\/code> package, or pass the data through a channel so only one goroutine owns it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q59. What is the context package used for?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>context<\/code> package carries cancellation signals, deadlines and request-scoped values across function calls and goroutines. For example, when an HTTP client disconnects, the server can cancel all the work started for that request.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Cancellation with <code>context.WithCancel<\/code><\/li>\n\n\n\n<li>Timeouts and deadlines with <code>context.WithTimeout<\/code> and <code>context.WithDeadline<\/code><\/li>\n\n\n\n<li>Request-scoped values with <code>context.WithValue<\/code> (for things like a request ID, not for normal parameters)<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Always call the <code>cancel<\/code> function, usually with <code>defer<\/code>, so resources are freed. Here is a timeout example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\n\/\/ slowWork pretends to do work that takes 2 seconds.\nfunc slowWork(ctx context.Context) error {\n    select {\n    case &lt;-time.After(2 * time.Second):\n        return nil\n    case &lt;-ctx.Done(): \/\/ the context was 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 release the context\n\n    err := slowWork(ctx)\n    fmt.Println(\"result:\", err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>result: context deadline exceeded<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">By convention, <code>ctx context.Context<\/code> is the first parameter of a function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q60. What is the select statement?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>select<\/code> lets a goroutine wait on several channel operations at once. The syntax looks like <code>switch<\/code>, but each case is a send or a receive on a channel. It blocks until one of the cases can go ahead, and then it runs that case.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It works only with channel operations.<\/li>\n\n\n\n<li>If several cases are ready, Go picks one at random, not the first one written.<\/li>\n\n\n\n<li>A <code>default<\/code> case runs when no other case is ready, so the select does not block.<\/li>\n\n\n\n<li>An empty <code>select {}<\/code> blocks forever.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You use <code>select<\/code> to wait on many channels, to add timeouts, to do non-blocking sends and receives, and to stop on <code>ctx.Done()<\/code>. Here is a timeout and a non-blocking receive.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    results := make(chan string) \/\/ nobody ever sends here\n\n    \/\/ 1. Timeout: wait for a result, but give up after 100 ms.\n    select {\n    case msg := &lt;-results:\n        fmt.Println(\"got:\", msg)\n    case &lt;-time.After(100 * time.Millisecond):\n        fmt.Println(\"timeout\")\n    }\n\n    \/\/ 2. Non-blocking receive with default.\n    select {\n    case msg := &lt;-results:\n        fmt.Println(\"got:\", msg)\n    default:\n        fmt.Println(\"no message ready\")\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>timeout\nno message ready<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q61. What is the difference between a process and a thread?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A process is a running program with its own memory space. A thread is a path of execution inside a process, and all threads in a process share the same memory. So threads are lighter than processes, and switching between them is faster.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Process<\/th><th>Thread<\/th><\/tr><\/thead><tbody><tr><td>Independent program with its own memory<\/td><td>Runs inside a process and shares its memory<\/td><\/tr><tr><td>Uses more memory<\/td><td>Uses less memory<\/td><\/tr><tr><td>Slower to create and to switch<\/td><td>Faster to create and to switch<\/td><\/tr><tr><td>A crash usually affects only that process<\/td><td>A crash can bring down the whole process<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Goroutines are lighter still. The Go runtime runs many goroutines on a few OS threads, and switching between goroutines happens in user space, without the kernel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q62. How does the Go scheduler work (the GMP model)?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The operating system schedules threads, not goroutines. So Go has its own scheduler inside the runtime. It maps many goroutines onto a small number of OS threads, and this design is called the GMP model.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>G (goroutine): your function, plus its stack and its state (runnable, running or waiting). It starts with a small stack of a few kilobytes that grows when needed.<\/li>\n\n\n\n<li>M (machine): a real OS thread. It runs Go code, one goroutine at a time.<\/li>\n\n\n\n<li>P (processor): a scheduling context with a local run queue of goroutines. An M must hold a P to run Go code. The number of Ps equals <code>GOMAXPROCS<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how it works step by step.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>You create a goroutine with <code>go f()<\/code>, and the runtime puts the new G in the current P&#8217;s local run queue.<\/li>\n\n\n\n<li>An M that holds a P takes a G from that queue and runs it.<\/li>\n\n\n\n<li>When the G blocks on a channel, a lock or a sleep, the scheduler parks it and runs the next G on the same M.<\/li>\n\n\n\n<li>When a G makes a blocking system call, the P is handed to another M, so other goroutines keep running.<\/li>\n\n\n\n<li>If a P&#8217;s queue is empty, it steals work from another P&#8217;s queue or takes it from the global run queue.<\/li>\n\n\n\n<li>Long-running goroutines are preempted (since Go 1.14, even tight loops), so one goroutine cannot block the others.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The benefits are cheap scheduling of huge numbers of goroutines, low memory use, good CPU use through work stealing, and blocking calls that do not stall the whole program.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q63. What is a channel deadlock?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A channel deadlock happens when goroutines wait on channels forever and nothing can ever wake them. If every goroutine in the program is blocked, the Go runtime stops the program with a fatal error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The classic case is sending on an unbuffered channel when no other goroutine will receive.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nfunc main() {\n    ch := make(chan int)\n    ch &lt;- 1 \/\/ blocks forever: nobody receives\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>fatal error: all goroutines are asleep - deadlock!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can fix it by receiving in another goroutine, by using a buffered channel with enough space, or by closing channels so <code>range<\/code> loops can end. However, the runtime only detects the case where all goroutines are stuck. If some goroutines are still running, a partial deadlock just hangs quietly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q64. What is sync.WaitGroup?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>sync.WaitGroup<\/code> waits for a group of goroutines to finish. The classic way is to call <code>Add(1)<\/code> before starting each goroutine, call <code>Done()<\/code> when it finishes, and call <code>Wait()<\/code> to block until the counter reaches zero.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    names := &#91;]string{\"alpha\", \"beta\", \"gamma\"}\n    lengths := make(&#91;]int, len(names)) \/\/ fixed slots keep output in order\n\n    var wg sync.WaitGroup\n    for i, name := range names {\n        wg.Add(1) \/\/ add before starting the goroutine\n        go func() {\n            defer wg.Done() \/\/ tell the WaitGroup this goroutine is done\n            lengths&#91;i] = len(name)\n        }()\n    }\n    wg.Wait() \/\/ block until all three goroutines call Done\n\n    for i, name := range names {\n        fmt.Println(name, lengths&#91;i])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>alpha 5\nbeta 4\ngamma 5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.25 there is also a <code>Go<\/code> method. It calls <code>Add<\/code> and <code>Done<\/code> for you, so you cannot forget 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(&#91;]int, 3)\n\n    for i := range 3 {\n        wg.Go(func() { \/\/ Add(1), go, and Done in one call (Go 1.25+)\n            results&#91;i] = i * 10\n        })\n    }\n    wg.Wait()\n\n    fmt.Println(results) \/\/ &#91;0 10 20]\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Never copy a WaitGroup after you start using it. If you pass it to a function, pass a pointer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q65. What are worker pools in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A worker pool is a pattern where a fixed number of goroutines (workers) take jobs from a shared channel. So you limit how many tasks run at once, instead of starting one goroutine per job. It is common in APIs, job processing and background tasks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a pool of 3 workers handling 6 jobs. Results go into a slice indexed by job number, so the output is always in order.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc worker(jobs &lt;-chan int, results &#91;]int, wg *sync.WaitGroup) {\n    defer wg.Done()\n    for job := range jobs { \/\/ loop ends when the jobs channel is closed\n        results&#91;job] = job * job\n    }\n}\n\nfunc main() {\n    const numJobs = 6\n    const numWorkers = 3\n\n    jobs := make(chan int, numJobs)\n    results := make(&#91;]int, numJobs)\n\n    var wg sync.WaitGroup\n    for range numWorkers {\n        wg.Add(1)\n        go worker(jobs, results, &amp;wg)\n    }\n\n    for j := range numJobs {\n        jobs &lt;- j\n    }\n    close(jobs) \/\/ no more jobs, workers can stop\n\n    wg.Wait()\n    fmt.Println(\"results:\", results)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>results: &#91;0 1 4 9 16 25]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q66. What is the difference between a timer and a ticker in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both come from the <code>time<\/code> package and both deliver times on a channel <code>C<\/code>. However, a <code>time.Timer<\/code> fires only once after a duration, and a <code>time.Ticker<\/code> fires again and again at a fixed interval.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th><code>time.Timer<\/code><\/th><th><code>time.Ticker<\/code><\/th><\/tr><\/thead><tbody><tr><td>Fires<\/td><td>Once, after the duration<\/td><td>Repeatedly, every interval<\/td><\/tr><tr><td>Channel<\/td><td><code>timer.C<\/code><\/td><td><code>ticker.C<\/code><\/td><\/tr><tr><td>Use case<\/td><td>Timeouts, delays<\/td><td>Polling, periodic jobs<\/td><\/tr><tr><td>Stop<\/td><td><code>timer.Stop()<\/code><\/td><td><code>ticker.Stop()<\/code><\/td><\/tr><tr><td>Reuse<\/td><td><code>timer.Reset(d)<\/code><\/td><td><code>ticker.Reset(d)<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.23, timers and tickers that you no longer reference are cleaned up by the garbage collector even if you never call <code>Stop<\/code>. Also, <code>Reset<\/code> and <code>Stop<\/code> no longer leave stale values in the channel. Still, calling <code>defer ticker.Stop()<\/code> is good practice.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    \/\/ Timer: fires once.\n    timer := time.NewTimer(30 * time.Millisecond)\n    &lt;-timer.C\n    fmt.Println(\"timer fired once\")\n\n    \/\/ Ticker: fires every 10 ms until we stop it.\n    ticker := time.NewTicker(10 * time.Millisecond)\n    defer ticker.Stop()\n\n    for i := 1; i &lt;= 3; i++ {\n        &lt;-ticker.C\n        fmt.Println(\"tick\", i)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>timer fired once\ntick 1\ntick 2\ntick 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q67. What is the difference between select and switch in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>switch<\/code> picks a branch by comparing values or checking conditions. It never waits. <code>select<\/code> picks a branch based on which channel operation is ready, and it waits if none is ready (unless it has a <code>default<\/code> case).<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th><code>switch<\/code><\/th><th><code>select<\/code><\/th><\/tr><\/thead><tbody><tr><td>Used for<\/td><td>Matching values or conditions<\/td><td>Waiting on channel operations<\/td><\/tr><tr><td>Cases are<\/td><td>Expressions<\/td><td>Channel sends or receives<\/td><\/tr><tr><td>Blocks<\/td><td>Never<\/td><td>Yes, until a case is ready (or runs <code>default<\/code>)<\/td><\/tr><tr><td>Many matches<\/td><td>First matching case wins<\/td><td>Random choice among ready cases<\/td><\/tr><tr><td>Use case<\/td><td>Normal control flow<\/td><td>Concurrency and goroutine coordination<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ switch: compares values\n    x := 2\n    switch x {\n    case 1:\n        fmt.Println(\"one\")\n    case 2:\n        fmt.Println(\"two\")\n    default:\n        fmt.Println(\"other\")\n    }\n\n    \/\/ select: waits for a ready channel\n    ch1 := make(chan string, 1)\n    ch2 := make(chan string, 1)\n    ch1 &lt;- \"from ch1\" \/\/ only ch1 has a value\n\n    select {\n    case msg := &lt;-ch1:\n        fmt.Println(\"received:\", msg)\n    case msg := &lt;-ch2:\n        fmt.Println(\"received:\", msg)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>two\nreceived: from ch1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q68. Why do you lock a mutex and then release it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go programs are concurrent, so many goroutines may read and write the same variables at once. Without synchronisation this causes race conditions, broken data and unpredictable bugs. <code>Lock()<\/code> and the matching release call make sure only one goroutine at a time is inside the critical section.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>mu.Lock()<\/code> takes the mutex. If another goroutine holds it, the caller waits.<\/li>\n\n\n\n<li>The release call gives the mutex back, so one waiting goroutine can continue.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The safest habit is to release with <code>defer<\/code> right after locking. Then the lock is freed even if the function returns early or panics.<\/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()         \/\/ take the lock\n    defer c.mu.Unlock() \/\/ always release it, even on early return\n    c.count++           \/\/ critical section\n}\n\nfunc main() {\n    var c Counter\n    var wg sync.WaitGroup\n\n    for range 2 {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for range 1000 {\n                c.Increment()\n            }\n        }()\n    }\n    wg.Wait()\n\n    fmt.Println(\"count:\", c.count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>count: 2000<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Rule<\/th><th>Why it matters<\/th><\/tr><\/thead><tbody><tr><td>Always release after every <code>Lock()<\/code><\/td><td>Otherwise other goroutines wait forever<\/td><\/tr><tr><td>Release with <code>defer<\/code><\/td><td>It still runs on early return or panic<\/td><\/tr><tr><td>Keep the locked section small<\/td><td>Less waiting, better performance<\/td><\/tr><tr><td>Do not copy a struct that holds a mutex<\/td><td>The copy has its own lock and protects nothing<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You use this pattern for shared counters, maps and slices written by many goroutines, shared caches, and any other state touched by more than one goroutine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q69. If I create two receiver channels for different goroutines, will it work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Each channel is independent, so two goroutines reading from two different channels do not interfere with each other.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are three cases to keep in mind.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Separate channels: each goroutine reads its own channel and gets only its own messages.<\/li>\n\n\n\n<li>One channel, many receivers: Go hands each message to exactly one receiver. So the work is shared out, like load balancing.<\/li>\n\n\n\n<li>Same data for every receiver: a channel does not copy a message to all readers. Instead, you fan out by sending a copy to each receiver&#8217;s channel, or you use a pub\/sub design.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the second case. Two workers read from one channel, and every job is handled exactly once.<\/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)\n    handled := make(&#91;]int, 2) \/\/ how many jobs each worker handled\n\n    var wg sync.WaitGroup\n    for w := range 2 {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for range jobs {\n                handled&#91;w]++ \/\/ each worker counts only into its own slot\n            }\n        }()\n    }\n\n    for j := 1; j &lt;= 10; j++ {\n        jobs &lt;- j \/\/ each value goes to only one worker\n    }\n    close(jobs)\n    wg.Wait()\n\n    fmt.Println(\"total jobs handled:\", handled&#91;0]+handled&#91;1])\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>total jobs handled: 10<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The split between the two workers can change from run to run, but the total is always 10.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q70. How do you limit the number of goroutines in a project?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Goroutines are cheap, but starting an unlimited number can still use too much memory, CPU, open files or database connections. So you put a limit on how many run at once. There are three common ways.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>A buffered channel used as a semaphore. Good for small projects and simple APIs.<\/li>\n\n\n\n<li>A worker pool with a fixed number of workers. Good for batch jobs and pipelines.<\/li>\n\n\n\n<li><code>errgroup.Group<\/code> with <code>SetLimit<\/code>. Good when you also need error handling and cancellation.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the semaphore approach. The channel has 3 slots, so at most 3 tasks run at the same time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nfunc main() {\n    const maxRunning = 3\n    sem := make(chan struct{}, maxRunning) \/\/ 3 free slots\n\n    results := make(&#91;]string, 8)\n    var wg sync.WaitGroup\n\n    for i := range results {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            sem &lt;- struct{}{}        \/\/ take a slot, wait if all 3 are busy\n            defer func() { &lt;-sem }() \/\/ give the slot back\n\n            time.Sleep(10 * time.Millisecond) \/\/ pretend to work\n            results&#91;i] = fmt.Sprintf(\"task %d done\", i)\n        }()\n    }\n    wg.Wait()\n\n    for _, r := range results {\n        fmt.Println(r)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>task 0 done\ntask 1 done\ntask 2 done\ntask 3 done\ntask 4 done\ntask 5 done\ntask 6 done\ntask 7 done<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>errgroup<\/code> package lives in <code>golang.org\/x\/sync<\/code>, which is an external module.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \"golang.org\/x\/sync\/errgroup\"\n\nvar g errgroup.Group\ng.SetLimit(3) \/\/ at most 3 goroutines at once\n\nfor _, url := range urls {\n    g.Go(func() error {\n        return fetch(url)\n    })\n}\nif err := g.Wait(); err != nil { \/\/ first error, after all goroutines finish\n    log.Println(\"failed:\", err)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q71. How do you call multiple goroutines from main(), each doing a separate task?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You start each task with the <code>go<\/code> keyword and use a <code>sync.WaitGroup<\/code> so <code>main<\/code> waits for all of them. If <code>main<\/code> returns early, the program exits and kills every goroutine that is still running.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each task below has a different delay, so they would finish in a random order. Because each task writes its message into its own slot, the printed result stays in order.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\n\/\/ simulateTask pretends to do some work and returns a report.\nfunc simulateTask(name string, delay time.Duration) string {\n    for step := 1; step &lt;= 3; step++ {\n        time.Sleep(delay) \/\/ one step of work\n    }\n    return name + \" completed 3 steps\"\n}\n\nfunc main() {\n    tasks := &#91;]struct {\n        name  string\n        delay time.Duration\n    }{\n        {\"Task 1\", 5 * time.Millisecond},\n        {\"Task 2\", 3 * time.Millisecond},\n        {\"Task 3\", 7 * time.Millisecond},\n        {\"Task 4\", 4 * time.Millisecond},\n    }\n    reports := make(&#91;]string, len(tasks))\n\n    var wg sync.WaitGroup\n    for i, t := range tasks {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            reports&#91;i] = simulateTask(t.name, t.delay)\n        }()\n    }\n    wg.Wait() \/\/ wait for all four tasks\n\n    for _, r := range reports {\n        fmt.Println(r)\n    }\n    fmt.Println(\"All tasks finished. Exiting main.\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Task 1 completed 3 steps\nTask 2 completed 3 steps\nTask 3 completed 3 steps\nTask 4 completed 3 steps\nAll tasks finished. Exiting main.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q72. How do you achieve parallelism in Go with a parallel computation?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You split the work into independent chunks and run each chunk in its own goroutine. When the machine has several cores, the runtime runs these goroutines at the same time. You do not need to call <code>runtime.GOMAXPROCS(runtime.NumCPU())<\/code>, because that is already the default.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here the program sums the numbers from 1 to 1,000,000 in 4 parallel chunks. Each goroutine stores its partial sum in its own slot, and then <code>main<\/code> adds the slots.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    const n = 1_000_000\n    const parts = 4\n\n    partial := make(&#91;]int, parts) \/\/ one slot per goroutine\n    chunk := n \/ parts\n\n    var wg sync.WaitGroup\n    for p := range parts {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            start := p*chunk + 1\n            end := start + chunk - 1\n            sum := 0\n            for i := start; i &lt;= end; i++ {\n                sum += i\n            }\n            partial&#91;p] = sum\n        }()\n    }\n    wg.Wait()\n\n    total := 0\n    for p, s := range partial {\n        fmt.Printf(\"part %d: %d\\n\", p, s)\n        total += s\n    }\n    fmt.Println(\"total:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>part 0: 31250125000\npart 1: 93750125000\npart 2: 156250125000\npart 3: 218750125000\ntotal: 500000500000<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Use<\/th><\/tr><\/thead><tbody><tr><td><code>go func()<\/code><\/td><td>Runs a goroutine concurrently<\/td><\/tr><tr><td><code>runtime.NumCPU()<\/code><\/td><td>Number of CPU cores the process can use<\/td><\/tr><tr><td><code>GOMAXPROCS<\/code><\/td><td>How many goroutines can run in parallel (defaults to the core count)<\/td><\/tr><tr><td><code>sync.WaitGroup<\/code><\/td><td>Waits for goroutines to finish<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Parallelism only helps with CPU-heavy work that splits into independent parts. For tiny tasks, the cost of starting goroutines can be more than the time you save.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q73. Where have you used a mutex in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use a mutex whenever several goroutines share data in memory. In real projects the common places are an in-memory cache, request counters and metrics, a shared job queue, a session or OTP store, and a rate limiter.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most common case is a cache. A <code>sync.RWMutex<\/code> fits well here, because many goroutines read and only a few write.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\ntype Cache struct {\n    mu   sync.RWMutex\n    data map&#91;string]string\n}\n\nfunc NewCache() *Cache {\n    return &amp;Cache{data: make(map&#91;string]string)}\n}\n\n\/\/ Get takes a read lock, so many readers can run together.\nfunc (c *Cache) Get(key string) (string, bool) {\n    c.mu.RLock()\n    defer c.mu.RUnlock()\n    val, ok := c.data&#91;key]\n    return val, ok\n}\n\n\/\/ Set takes a write lock, so it runs alone.\nfunc (c *Cache) Set(key, value string) {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.data&#91;key] = value\n}\n\nfunc main() {\n    cache := NewCache()\n\n    var wg sync.WaitGroup\n    for i := range 5 {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            cache.Set(fmt.Sprintf(\"user%d\", i), fmt.Sprintf(\"token%d\", i))\n        }()\n    }\n    wg.Wait()\n\n    for i := range 5 {\n        val, _ := cache.Get(fmt.Sprintf(\"user%d\", i))\n        fmt.Println(val)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>token0\ntoken1\ntoken2\ntoken3\ntoken4<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For one-time setup, such as opening a database connection, use <code>sync.Once<\/code> instead of a mutex. It runs the setup function exactly once, even when many goroutines call it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You do not need a mutex if only one goroutine touches the data, if a channel already hands the data from owner to owner, or if the database handles the locking for you. A simple rule of thumb is &#8220;use a mutex for state, use channels for flow&#8221;.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Mutex<\/th><th>Channel<\/th><\/tr><\/thead><tbody><tr><td>Protects shared memory<\/td><td>Passes data between goroutines (share by communicating)<\/td><\/tr><tr><td>Best for guarding state<\/td><td>Best for workflows and pipelines<\/td><\/tr><tr><td>Very low overhead<\/td><td>A bit more overhead, but clearer for hand-offs<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q74. How do you write an async function in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go has no <code>async<\/code> and <code>await<\/code> keywords. Instead, you run a function in a goroutine with the <code>go<\/code> keyword, and the caller keeps going without waiting. To get the result back, you usually return a channel, or you use a <code>sync.WaitGroup<\/code>, an <code>errgroup<\/code> or a <code>context<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a simple &#8220;future&#8221; style function that returns a channel.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"time\"\n)\n\n\/\/ fetchPrice starts the work in a goroutine and returns at once.\nfunc fetchPrice(item string) &lt;-chan int {\n    result := make(chan int, 1) \/\/ buffered so the goroutine never gets stuck\n    go func() {\n        time.Sleep(20 * time.Millisecond) \/\/ pretend this is a slow API call\n        result &lt;- len(item) * 100\n    }()\n    return result\n}\n\nfunc main() {\n    applePrice := fetchPrice(\"apple\") \/\/ both calls start right away\n    kiwiPrice := fetchPrice(\"kiwi\")\n\n    fmt.Println(\"doing other work...\")\n\n    \/\/ Now wait for the results.\n    fmt.Println(\"apple:\", &lt;-applePrice)\n    fmt.Println(\"kiwi:\", &lt;-kiwiPrice)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>doing other work...\napple: 500\nkiwi: 400<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When you run code this way, watch for three common problems.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Race conditions: several goroutines touch shared memory. So protect it with a mutex or use channels.<\/li>\n\n\n\n<li>Goroutine leaks: goroutines that never stop keep using memory. Stop them with a <code>context<\/code> or by closing channels.<\/li>\n\n\n\n<li>Deadlocks: goroutines that wait on each other forever. Plan who sends, who receives and who closes.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This style works well for API calls, file processing, background jobs, microservices and parallel computation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q75. How do you detect a race condition in your code?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The best tool is the Go race detector. You turn it on with the <code>-race<\/code> flag when you run, test or build your program.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go run -race main.go\ngo test -race .\/...\ngo build -race -o app .<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When the detector sees two goroutines touching the same memory without synchronisation, it prints a &#8220;WARNING: DATA RACE&#8221; report. The report shows both stack traces, so you can find the exact lines. However, it only finds races in code paths that actually run, so good tests matter. Also, it makes programs slower, so use it in tests and CI rather than in production.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Even without the detector, some signs point to a race.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Output that changes from run to run<\/li>\n\n\n\n<li>Values that are wrong or impossible<\/li>\n\n\n\n<li>Random crashes, such as &#8220;concurrent map writes&#8221;<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q76. What is a goroutine leak?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A goroutine leak happens when a goroutine keeps running or stays blocked after you no longer need it. It never exits, so its stack and the memory it points to are never freed. Over time, leaks make memory use grow until the service slows down or crashes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Common causes are a goroutine blocked on a channel that nobody will send to or receive from, a loop with no exit condition, and work that ignores cancellation. You can fix them in these ways.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Pass a <code>context<\/code> and stop when <code>ctx.Done()<\/code> is closed (for example with <code>context.WithCancel<\/code>).<\/li>\n\n\n\n<li>Close channels when there is no more data, so <code>range<\/code> loops end.<\/li>\n\n\n\n<li>Give every loop a clear exit path.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n)\n\nfunc worker(ctx context.Context, jobs &lt;-chan int, wg *sync.WaitGroup) {\n    defer wg.Done()\n    for {\n        select {\n        case &lt;-ctx.Done(): \/\/ stop when the caller cancels\n            fmt.Println(\"worker stopped:\", ctx.Err())\n            return\n        case j := &lt;-jobs:\n            fmt.Println(\"processed job\", j)\n        }\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    jobs := make(chan int)\n\n    var wg sync.WaitGroup\n    wg.Add(1)\n    go worker(ctx, jobs, &amp;wg)\n\n    jobs &lt;- 1\n    jobs &lt;- 2\n\n    cancel()  \/\/ without this, the worker would wait on jobs forever\n    wg.Wait() \/\/ make sure it really exited\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>processed job 1\nprocessed job 2\nworker stopped: context canceled<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q77. What is context switching?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Context switching is when the CPU stops running one process or thread and starts running another. First the system saves the state of the current task, such as its registers and program counter. Then it loads the saved state of the next task.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A switch between OS threads goes through the kernel, so it is fairly costly. Goroutine switches are much cheaper, because the Go scheduler does them in user space and saves only a few registers. This is one reason Go can run so many goroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q78. What happens if you forget to release a mutex lock?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Every other goroutine that calls <code>Lock()<\/code> on that mutex waits forever. If all goroutines end up stuck this way, the runtime stops with &#8220;all goroutines are asleep &#8211; deadlock!&#8221;. If only some are stuck, your program just hangs or stops responding.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The fix is to release the lock with <code>defer<\/code> straight after taking it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mu.Lock()\ndefer mu.Unlock() \/\/ runs on every return path, even on panic\n\n\/\/ critical section<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q79. What is the difference between Mutex and RWMutex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sync.Mutex<\/code> lets only one goroutine hold the lock, whether it reads or writes. <code>sync.RWMutex<\/code> lets many readers hold a read lock at the same time, but a writer gets the lock alone.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><code>sync.Mutex<\/code><\/th><th><code>sync.RWMutex<\/code><\/th><\/tr><\/thead><tbody><tr><td>One goroutine at a time, for reads and writes<\/td><td>Many readers at once, or one writer<\/td><\/tr><tr><td>Simpler and slightly faster per call<\/td><td>Better for read-heavy workloads<\/td><\/tr><tr><td>Methods: <code>Lock()<\/code> and its release method<\/td><td><code>RLock()<\/code> \/ <code>RUnlock()<\/code> for reads, plus the write lock pair<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>RWMutex<\/code> only when reads are much more common than writes, for example a cache or a config store. Otherwise, a plain <code>Mutex<\/code> is simpler and often just as fast.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q80. What is a deadlock?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A deadlock is when two or more goroutines are blocked forever, each waiting for something that will never happen. So the program cannot make progress. If every goroutine is blocked, Go stops the program with a fatal error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The simplest example is a send on an unbuffered channel with no receiver.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nfunc main() {\n    ch := make(chan int)\n    ch &lt;- 10 \/\/ blocks forever\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>fatal error: all goroutines are asleep - deadlock!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This happens because an unbuffered channel needs a receiver. No goroutine is receiving, so the send waits forever. Other common causes are two goroutines that take two mutexes in opposite order, and a <code>wg.Wait()<\/code> whose matching <code>Done()<\/code> calls never come.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q81. Does GMP increase or decrease the number of threads?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Neither, really. The goal of GMP is to run a large number of goroutines on a small number of OS threads. So the runtime keeps threads few and changes their number only when it needs to.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It adds threads when needed. For example, when a thread blocks in a system call (like file I\/O), the runtime hands its P to another thread so other goroutines keep running.<\/li>\n\n\n\n<li>It reuses threads. When the blocked thread is free again, it goes back to a pool of idle threads instead of being thrown away.<\/li>\n\n\n\n<li>At most <code>GOMAXPROCS<\/code> threads run Go code at once. Extra threads exist only for blocked system calls.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In an interview you can say this. &#8220;GMP does not just add or remove threads. It schedules many goroutines onto a few OS threads, creates extra threads only when one blocks, and reuses threads whenever it can.&#8221;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q82. Which channel is synchronous in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An unbuffered channel is synchronous. The sender and the receiver must meet at the same moment. So a send blocks until another goroutine receives, and a receive blocks until another goroutine sends.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A buffered channel is asynchronous up to its capacity. A send goes ahead without a receiver as long as the buffer has space. Once the buffer is full, sends block until a receiver takes a value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    buffered := make(chan string, 1)\n    buffered &lt;- \"hello\" \/\/ works with no receiver, because there is space\n    fmt.Println(\"buffered send done\")\n    fmt.Println(&lt;-buffered)\n\n    unbuffered := make(chan string)\n    go func() {\n        unbuffered &lt;- \"hi\" \/\/ waits here until main receives\n    }()\n    fmt.Println(&lt;-unbuffered) \/\/ the hand-off happens here\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>buffered send done\nhello\nhi<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q83. What does synchronous mean?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Synchronous means one operation waits for another to finish before it continues. For example, a normal function call is synchronous, because the caller waits for the function to return.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, an unbuffered channel is synchronous. The sender blocks until a receiver is ready, and the receiver blocks until a sender provides a value. So both goroutines meet at the point of communication. The opposite is asynchronous, where the caller starts the work and carries on without waiting, like starting a goroutine with <code>go<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Memory, GC and Performance<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Golang questions and answers cover how Go manages memory, how the garbage collector works and how you keep a Go service fast. You will also see how to find and fix memory leaks, CPU spikes and slow responses.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q84. What is garbage collection in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Garbage collection (GC) is automatic memory management. Go finds memory that your program can no longer reach and frees it for you. So you never call <code>free<\/code> like you do in C or C++.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go uses a concurrent, tri-colour mark and sweep collector. It runs mostly in the background, at the same time as your goroutines. Because of this, the &#8220;stop the world&#8221; pauses are very short, usually well under a millisecond.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is why garbage collection helps you.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It removes most manual memory bugs, such as double free and use after free.<\/li>\n\n\n\n<li>It lowers the risk of memory leaks, but it cannot remove all of them.<\/li>\n\n\n\n<li>You write less code, so you get more done.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can tune the collector with two settings. <code>GOGC<\/code> (default 100) controls how much the heap may grow before the next cycle. <code>GOMEMLIMIT<\/code> sets a soft memory limit, which is useful in containers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q85. What is mark and sweep in Go&#8217;s garbage collector?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Mark and sweep is the method Go&#8217;s GC uses to find and free unused memory. It works in two phases.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Mark phase. The GC starts from the roots (globals, stacks and registers) and follows every pointer. Each object it can reach is marked as live.<\/li>\n\n\n\n<li>Sweep phase. The GC walks the heap and frees every object that was not marked. That memory goes back to Go&#8217;s allocator for reuse.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Think of it like cleaning your desk. First, you tag the papers you still need. Then you throw away everything without a tag.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The &#8220;tri-colour&#8221; part describes how marking is tracked. White objects are not yet seen, grey objects are seen but their pointers are not yet scanned, and black objects are fully scanned. When no grey objects remain, every white object is garbage. A write barrier keeps this correct while your code changes pointers during marking.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go&#8217;s collector does not compact memory, so it never moves objects around. Since Go 1.26, the default collector also uses the &#8220;Green Tea&#8221; design. It scans memory in small pages for better CPU cache use, but the idea is still mark and sweep.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">People sometimes mix this up with <code>make<\/code>. However, <code>make<\/code> is not part of the GC. It is a built-in function that allocates and sets up slices, maps and channels so they are ready to use. When nothing refers to that slice, map or channel any more, the GC frees it in a later cycle.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ make allocates and initialises a slice, a map and a channel.\n    scores := make(&#91;]int, 3)\n    ages := make(map&#91;string]int)\n    jobs := make(chan string, 2)\n\n    ages&#91;\"Asha\"] = 30\n    jobs &lt;- \"build\"\n\n    fmt.Println(len(scores), len(ages), len(jobs))\n\n    \/\/ new only allocates zeroed memory and returns a pointer.\n    count := new(int)\n    fmt.Println(*count)\n\n    \/\/ After this, nothing refers to the old slice, so the GC can free it.\n    scores = nil\n    fmt.Println(scores == nil)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3 1 1\n0\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q86. How do you avoid memory leaks in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most leaks in Go come from things that stay referenced or never stop. So the fix is to give every resource and every goroutine a clear end.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Stop goroutines. A goroutine that waits forever on a channel leaks. Give it a way to stop, such as <code>context.Context<\/code> or a done channel.<\/li>\n\n\n\n<li>Close channels when the sender is finished, so receivers can exit their <code>range<\/code> loops.<\/li>\n\n\n\n<li>Drop references you no longer need. For example, set a large global value to <code>nil<\/code> or remove old keys from a map.<\/li>\n\n\n\n<li>Close files, database rows, HTTP response bodies and network connections. Use <code>defer<\/code> right after you open them.<\/li>\n\n\n\n<li>Watch your service with <code>pprof<\/code> and the goroutine count, so you spot growth early.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a worker that stops cleanly when its context is cancelled.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n)\n\nfunc worker(ctx context.Context, jobs &lt;-chan int, done chan&lt;- string) {\n    for {\n        select {\n        case &lt;-ctx.Done():\n            \/\/ Context cancelled, so the goroutine exits and frees its memory.\n            done &lt;- \"worker stopped\"\n            return\n        case job := &lt;-jobs:\n            fmt.Println(\"processed job\", job)\n        }\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    jobs := make(chan int)\n    done := make(chan string)\n\n    go worker(ctx, jobs, done)\n\n    jobs &lt;- 1\n    jobs &lt;- 2\n\n    cancel() \/\/ tell the worker to stop\n    fmt.Println(&lt;-done)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>processed job 1\nprocessed job 2\nworker stopped<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q87. How do you reduce GC overhead in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The GC has more work when you allocate a lot and when the heap holds many pointers. So you reduce overhead by allocating less and keeping data simple.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reuse objects with <code>sync.Pool<\/code>, for example buffers in a busy HTTP handler.<\/li>\n\n\n\n<li>Preallocate slices and maps when you know the size, such as <code>make([]int, 0, 1000)<\/code>.<\/li>\n\n\n\n<li>Avoid needless pointers. A slice of structs is cheaper to scan than a slice of pointers to structs.<\/li>\n\n\n\n<li>Avoid building strings in a loop with <code>+<\/code>. Use <code>strings.Builder<\/code> instead.<\/li>\n\n\n\n<li>Tune <code>GOGC<\/code> and <code>GOMEMLIMIT<\/code> if profiling shows the GC uses too much CPU.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small example that reuses buffers with <code>sync.Pool<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ bufferPool hands out reusable buffers instead of allocating new ones.\nvar bufferPool = sync.Pool{\n    New: func() any {\n        return new(bytes.Buffer)\n    },\n}\n\nfunc greet(name string) string {\n    buf := bufferPool.Get().(*bytes.Buffer)\n    buf.Reset() \/\/ clear old data before use\n    defer bufferPool.Put(buf)\n\n    buf.WriteString(\"Hello, \")\n    buf.WriteString(name)\n    return buf.String()\n}\n\nfunc main() {\n    fmt.Println(greet(\"Go\"))\n    fmt.Println(greet(\"Gopher\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Hello, Go\nHello, Gopher<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q88. Does the garbage collector prevent memory leaks?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No, not always. The GC only frees memory that nothing refers to. If your code still holds a reference, the GC must keep that memory, even if you will never use it again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the usual causes of leaks in Go.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Goroutines that are stuck forever on a channel, a lock or a network call.<\/li>\n\n\n\n<li>Resources you never close, such as files, response bodies or database rows.<\/li>\n\n\n\n<li>Maps and caches that grow without any limit.<\/li>\n\n\n\n<li>A small sub-slice that keeps a huge backing array alive.<\/li>\n\n\n\n<li>Global variables that hold large data for the whole life of the program.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">So you still need good habits. Close resources with <code>defer<\/code>, and control goroutines with context cancellation, timeouts and worker pools. Also, put a size limit on caches and be careful with very large channel buffers. Then check heap and goroutine profiles with <code>pprof<\/code> to confirm nothing keeps growing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q89. What is escape analysis in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Escape analysis is a compiler step that decides where a variable lives, on the stack or on the heap. The Go compiler does this at compile time, so you do not choose it yourself.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Stack. Allocation is very fast, and the memory is freed when the function returns. It is used for values that do not outlive the function.<\/li>\n\n\n\n<li>Heap. Allocation is slower, and the GC frees the memory later. It is used when a value must live after the function returns.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A value &#8220;escapes&#8221; to the heap when the compiler cannot prove it stays inside the function. For example, returning a pointer to a local variable makes it escape. Storing a value in an interface or a global can also make it escape.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype User struct {\n    Name string\n}\n\n\/\/ newUser returns a pointer, so u escapes to the heap.\nfunc newUser(name string) *User {\n    u := User{Name: name}\n    return &amp;u\n}\n\n\/\/ sum keeps total on the stack because it never leaves the function.\nfunc sum(nums &#91;]int) int {\n    total := 0\n    for _, n := range nums {\n        total += n\n    }\n    return total\n}\n\nfunc main() {\n    u := newUser(\"Asha\")\n    fmt.Println(u.Name)\n    fmt.Println(sum(&#91;]int{1, 2, 3}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha\n6<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can see the compiler&#8217;s decisions with the <code>-gcflags=-m<\/code> flag.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go build -gcflags=-m .\n# .\/main.go:11:2: moved to heap: u<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Escape analysis matters because fewer heap allocations mean less GC work. As a result, your program runs faster without any manual memory code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q90. What is a memory leak?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A memory leak happens when a program keeps holding memory it no longer needs. That memory cannot be reused, so memory use grows over time. Finally, this can slow the service down or make it crash with an out of memory error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In C or C++, a leak usually means you forgot to call <code>free<\/code>. In Go, the GC frees unreachable memory for you. So a Go leak usually means your program still has a reference to data it no longer needs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a common case. A small sub-slice keeps the whole large backing array alive. Copying the part you need lets the GC free the big array.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ firstThreeLeaky returns a sub-slice that still points at the big array.\nfunc firstThreeLeaky(big &#91;]byte) &#91;]byte {\n    return big&#91;:3]\n}\n\n\/\/ firstThreeSafe copies the bytes, so the big array can be collected.\nfunc firstThreeSafe(big &#91;]byte) &#91;]byte {\n    small := make(&#91;]byte, 3)\n    copy(small, big&#91;:3])\n    return small\n}\n\nfunc main() {\n    big := make(&#91;]byte, 1_000_000)\n\n    leaky := firstThreeLeaky(big)\n    safe := firstThreeSafe(big)\n\n    fmt.Println(\"leaky cap:\", cap(leaky))\n    fmt.Println(\"safe cap:\", cap(safe))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>leaky cap: 1000000\nsafe cap: 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how you prevent leaks.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Remove references to objects you no longer need.<\/li>\n\n\n\n<li>Close files, database rows and network connections.<\/li>\n\n\n\n<li>Stop goroutines with <code>context.Context<\/code> or a done channel.<\/li>\n\n\n\n<li>Put limits on slices, maps and caches that grow over time.<\/li>\n\n\n\n<li>Close channels when the sender is done.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To find leaks, expose <code>net\/http\/pprof<\/code> in your service and read the heap and goroutine profiles.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go tool pprof http:\/\/localhost:6060\/debug\/pprof\/heap\ngo tool pprof http:\/\/localhost:6060\/debug\/pprof\/goroutine<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also read memory stats from inside your program.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var m runtime.MemStats\nruntime.ReadMemStats(&amp;m)\nfmt.Println(\"heap in use (bytes):\", m.HeapAlloc)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q91. What causes a CPU spike, and how do you handle it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A CPU spike is a sudden jump in CPU use. In a Go service it usually comes from one of these causes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A burst of traffic, so more requests run at the same time.<\/li>\n\n\n\n<li>Slow code, such as nested loops, heavy JSON work or regex compiled on every request.<\/li>\n\n\n\n<li>Too many goroutines doing work at once, with no limit.<\/li>\n\n\n\n<li>A lot of garbage collection, because the code allocates too much.<\/li>\n\n\n\n<li>Busy loops or retry storms that never wait between tries.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">First, confirm the spike with system metrics, for example in Prometheus and Grafana. Next, take a CPU profile to see which functions use the most time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go tool pprof http:\/\/localhost:6060\/debug\/pprof\/profile?seconds=30<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then fix the hot path. You can optimise the code, cache results, cut allocations and limit concurrency with a worker pool. Also, add rate limiting and autoscaling so traffic bursts do not overload a single instance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q92. How do you reduce latency in a Go service?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Latency is the time a request takes from start to finish. You reduce it by removing slow work from the request path.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Cache data that is read often, in memory or in Redis.<\/li>\n\n\n\n<li>Reduce database calls. For example, fetch data in one query instead of many small ones.<\/li>\n\n\n\n<li>Use connection pooling, which <code>database\/sql<\/code> and <code>net\/http<\/code> do for you.<\/li>\n\n\n\n<li>Optimise queries with the right indexes, and select only the columns you need.<\/li>\n\n\n\n<li>Run independent calls in parallel with goroutines, then wait for all of them.<\/li>\n\n\n\n<li>Set timeouts with <code>context<\/code> so one slow dependency cannot block everything.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Always measure first with metrics or <code>pprof<\/code>. Then you fix the real bottleneck instead of guessing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q93. What is the difference between a memory leak and a goroutine leak?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A memory leak means data stays referenced, so the GC cannot free it. A goroutine leak means goroutines stay blocked or running forever. Also, a goroutine leak is a kind of memory leak, because each stuck goroutine keeps its stack and every value it refers to.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Memory leak<\/th><th>Goroutine leak<\/th><\/tr><\/thead><tbody><tr><td>Unused memory stays referenced and cannot be collected<\/td><td>Goroutines stay blocked or running forever<\/td><\/tr><tr><td>Heap usage keeps growing<\/td><td>The goroutine count keeps growing<\/td><\/tr><tr><td>Mostly affects memory and GC time<\/td><td>Affects memory, scheduling and CPU<\/td><\/tr><tr><td>Found with the heap profile<\/td><td>Found with the goroutine profile or <code>runtime.NumGoroutine<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a goroutine leak in action. Each goroutine waits on a channel that nobody ever sends to.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"runtime\"\n)\n\nfunc leak() {\n    ch := make(chan int)\n    go func() {\n        &lt;-ch \/\/ blocks forever, because nothing sends on ch\n    }()\n}\n\nfunc main() {\n    before := runtime.NumGoroutine()\n    for i := 0; i &lt; 3; i++ {\n        leak()\n    }\n    after := runtime.NumGoroutine()\n    fmt.Println(\"leaked goroutines:\", after-before)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>leaked goroutines: 3<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Web, REST APIs and Security<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Golang questions and answers cover building web servers and REST APIs in Go, from routing and middleware to frameworks like Gin and Fiber. You will also learn the security basics, such as CORS, JWT, OAuth, authentication and authorization.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q94. What is middleware in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Middleware is a function that wraps your handler. It runs before your handler, after it, or both. So it can read or change the request and the response in one shared place.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can use middleware with plain <code>net\/http<\/code> or with frameworks like Gin, Fiber and Echo. Here are common uses.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Logging requests<\/li>\n\n\n\n<li>Authentication and authorization<\/li>\n\n\n\n<li>Request validation<\/li>\n\n\n\n<li>Adding CORS headers<\/li>\n\n\n\n<li>Rate limiting<\/li>\n\n\n\n<li>Compressing responses<\/li>\n\n\n\n<li>Recovering from panics<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In <code>net\/http<\/code>, middleware takes an <code>http.Handler<\/code> and returns a new <code>http.Handler<\/code>. Here is a logging middleware tested with <code>httptest<\/code>, so no real server is needed.<\/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 next and prints a line before and after it runs.\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)\n        fmt.Println(\"after:\", r.URL.Path)\n    })\n}\n\nfunc hello(w http.ResponseWriter, r *http.Request) {\n    fmt.Println(\"handler running\")\n    fmt.Fprint(w, \"Hello\")\n}\n\nfunc main() {\n    handler := logging(http.HandlerFunc(hello))\n\n    req := httptest.NewRequest(http.MethodGet, \"\/hello\", nil)\n    rec := httptest.NewRecorder()\n    handler.ServeHTTP(rec, req)\n\n    fmt.Println(\"response:\", rec.Body.String())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>before: GET \/hello\nhandler running\nafter: \/hello\nresponse: Hello<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q95. What is CORS?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">CORS stands for Cross-Origin Resource Sharing. It is a browser security rule that controls whether a web page can call a server on a different origin. An origin is the mix of protocol, domain and port, so <code>https:\/\/app.com<\/code> and <code>https:\/\/api.app.com<\/code> are different origins.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default, browsers block these cross-origin calls from JavaScript. This protects users from harmful sites. CORS lets your server tell the browser which other origins it trusts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how it works.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The browser sends the request. For some requests it first sends a &#8220;preflight&#8221; <code>OPTIONS<\/code> request.<\/li>\n\n\n\n<li>The server replies with headers such as <code>Access-Control-Allow-Origin<\/code>, <code>Access-Control-Allow-Methods<\/code> and <code>Access-Control-Allow-Headers<\/code>.<\/li>\n\n\n\n<li>If the headers allow it, the browser lets the page read the response.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">CORS is enforced by the browser only. So it does not protect your API from tools like <code>curl<\/code>, and you still need authentication. Here is a simple CORS middleware in Go.<\/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\nconst allowedOrigin = \"https:\/\/myfrontend.com\"\n\n\/\/ cors adds CORS headers and answers preflight requests.\nfunc cors(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        if r.Header.Get(\"Origin\") == allowedOrigin {\n            w.Header().Set(\"Access-Control-Allow-Origin\", allowedOrigin)\n            w.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST\")\n            w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\")\n        }\n        if r.Method == http.MethodOptions {\n            w.WriteHeader(http.StatusNoContent) \/\/ preflight needs no body\n            return\n        }\n        next.ServeHTTP(w, r)\n    })\n}\n\nfunc main() {\n    api := cors(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprint(w, \"data\")\n    }))\n\n    req := httptest.NewRequest(http.MethodOptions, \"\/users\", nil)\n    req.Header.Set(\"Origin\", \"https:\/\/myfrontend.com\")\n    rec := httptest.NewRecorder()\n    api.ServeHTTP(rec, req)\n\n    fmt.Println(\"status:\", rec.Code)\n    fmt.Println(\"allow origin:\", rec.Header().Get(\"Access-Control-Allow-Origin\"))\n    fmt.Println(\"allow methods:\", rec.Header().Get(\"Access-Control-Allow-Methods\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>status: 204\nallow origin: https:\/\/myfrontend.com\nallow methods: GET, POST<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In real projects you can also use a ready package such as <code>github.com\/rs\/cors<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q96. What do you use to secure a REST API in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No single tool secures an API. Instead, you combine several layers.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Authentication (who you are). Use JWT for stateless APIs, OAuth 2.0 or OpenID Connect for third-party login, and API keys for service-to-service calls. Basic Auth is only acceptable over HTTPS.<\/li>\n\n\n\n<li>Authorization (what you can do). Use role-based access control (RBAC), such as admin and user roles. For finer rules, use attribute-based access control (ABAC).<\/li>\n\n\n\n<li>Transport security. Always use HTTPS (TLS), so nobody can read or change data in transit.<\/li>\n\n\n\n<li>Input validation. Check the body, query, headers and path values. Use parameterised SQL queries to stop SQL injection, and escape output to stop XSS.<\/li>\n\n\n\n<li>CORS. Allow only the origins, methods and headers you need.<\/li>\n\n\n\n<li>Rate limiting. Block brute force attacks and abuse with <code>golang.org\/x\/time\/rate<\/code>, or at a proxy like Nginx or Cloudflare.<\/li>\n\n\n\n<li>Logging and monitoring. Log failed logins and unusual activity, but never log passwords or tokens. Monitor with Prometheus and Grafana or the ELK stack.<\/li>\n\n\n\n<li>Data protection. Hash passwords with bcrypt or argon2, and encrypt sensitive data at rest.<\/li>\n\n\n\n<li>Middleware. Put auth checks, validation and panic recovery in middleware, so error pages never leak stack traces.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an auth middleware in Gin. It needs the Gin module, so it does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func AuthMiddleware() gin.HandlerFunc {\n    return func(c *gin.Context) {\n        token := strings.TrimPrefix(c.GetHeader(\"Authorization\"), \"Bearer \")\n        if !validateJWT(token) {\n            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n            return\n        }\n        c.Next() \/\/ token is valid, so continue to the handler\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In short, use HTTPS, JWT or OAuth, RBAC, rate limiting, input validation and logging together.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q97. How do you use OAuth with a third-party provider but allow only some users in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You let the provider prove who the user is. Then your own code decides if that user may come in. Here is the flow.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The user clicks &#8220;Sign in&#8221; and your app redirects them to the provider (Google, GitHub and so on) with your client ID.<\/li>\n\n\n\n<li>Next, the user logs in and grants permission.<\/li>\n\n\n\n<li>The provider redirects back to your app with a short-lived code.<\/li>\n\n\n\n<li>Your backend exchanges the code for tokens, using the client ID and client secret.<\/li>\n\n\n\n<li>You verify the ID token, or call the provider&#8217;s user info API, to get the email or user ID.<\/li>\n\n\n\n<li>You check that user against your own allowlist, in a database, a config file or a role table.<\/li>\n\n\n\n<li>If the user is allowed, you issue your own session or JWT. Otherwise, you return 403 Forbidden.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The client ID identifies your app to the provider. The client secret proves your app is genuine, so keep it on the server and never send it to the browser.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two libraries cover most needs. <code>golang.org\/x\/oauth2<\/code> handles the OAuth flow, and <code>github.com\/coreos\/go-oidc\/v3<\/code> verifies OpenID Connect ID tokens. Here is the code exchange step. It needs those modules, so it does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>conf := &amp;oauth2.Config{\n    ClientID:     os.Getenv(\"OAUTH_CLIENT_ID\"),\n    ClientSecret: os.Getenv(\"OAUTH_CLIENT_SECRET\"),\n    RedirectURL:  \"https:\/\/myapp.com\/auth\/callback\",\n    Scopes:       &#91;]string{\"openid\", \"email\"},\n    Endpoint:     google.Endpoint,\n}\n\n\/\/ In the callback handler, swap the code for tokens.\ntoken, err := conf.Exchange(r.Context(), r.URL.Query().Get(\"code\"))<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The allowlist check itself is plain Go.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ allowed holds the emails that may use the app.\nvar allowed = map&#91;string]bool{\n    \"asha@example.com\":  true,\n    \"ravi@example.com\":  true,\n}\n\nfunc isAllowed(email string) bool {\n    return allowed&#91;strings.ToLower(email)]\n}\n\nfunc main() {\n    for _, email := range &#91;]string{\"Asha@example.com\", \"guest@example.com\"} {\n        if isAllowed(email) {\n            fmt.Println(email, \"-&gt; access granted\")\n        } else {\n            fmt.Println(email, \"-&gt; 403 Forbidden\")\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha@example.com -&gt; access granted\nguest@example.com -&gt; 403 Forbidden<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q98. Which comes first, authentication or authorization?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Authentication always comes first, then authorization. The system cannot decide what you may do until it knows who you are.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Step<\/th><th>Meaning<\/th><th>Question it answers<\/th><\/tr><\/thead><tbody><tr><td>Authentication<\/td><td>Checks who the user is<\/td><td>&#8220;Are you really this user?&#8221;<\/td><\/tr><tr><td>Authorization<\/td><td>Checks what the user may do<\/td><td>&#8220;What are you allowed to do?&#8221;<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the order in a real flow.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The user logs in with a username and password (authentication).<\/li>\n\n\n\n<li>The system confirms the identity and creates a token or session.<\/li>\n\n\n\n<li>On each request, the system checks the user&#8217;s roles and permissions (authorization).<\/li>\n\n\n\n<li>The user is allowed or denied access to the feature.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Think of an office. At the gate, security checks your ID card, which is authentication. Inside, your access card decides which floors you can enter, which is authorization.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q99. What is a 401 API response?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">HTTP 401 Unauthorized means the request lacks valid authentication. The name is confusing, because it really means &#8220;unauthenticated&#8221;. You usually get a 401 in these cases.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No token was sent, or the <code>Authorization<\/code> header is missing.<\/li>\n\n\n\n<li>An expired token was sent.<\/li>\n\n\n\n<li>The token is invalid or malformed.<\/li>\n\n\n\n<li>The username or password is wrong.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A 401 response often looks like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"error\": \"unauthorized\",\n  \"message\": \"invalid or missing token\"\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">People often mix up 401 and 403.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Status<\/th><th>Meaning<\/th><th>Cause<\/th><\/tr><\/thead><tbody><tr><td>401 Unauthorized<\/td><td>Authentication failed<\/td><td>The user is not logged in or the token is invalid<\/td><\/tr><tr><td>403 Forbidden<\/td><td>Authorization failed<\/td><td>The user is logged in but lacks permission<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how you fix a 401.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Problem<\/th><th>Solution<\/th><\/tr><\/thead><tbody><tr><td>Token not sent<\/td><td>Add <code>Authorization: Bearer &lt;token&gt;<\/code> to the header<\/td><\/tr><tr><td>Token expired<\/td><td>Use a refresh token or log in again<\/td><\/tr><tr><td>Invalid token<\/td><td>Get a new token<\/td><\/tr><tr><td>Wrong credentials<\/td><td>Correct the username or password<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">This Go handler returns 401 or 403 depending on the case.<\/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\/\/ tokens maps a token to its user role. A real app would verify a JWT.\nvar tokens = map&#91;string]string{\"admin-token\": \"admin\", \"user-token\": \"user\"}\n\nfunc adminOnly(w http.ResponseWriter, r *http.Request) {\n    role, ok := tokens&#91;r.Header.Get(\"Authorization\")]\n    if !ok {\n        http.Error(w, \"unauthorized\", http.StatusUnauthorized) \/\/ who are you?\n        return\n    }\n    if role != \"admin\" {\n        http.Error(w, \"forbidden\", http.StatusForbidden) \/\/ you may not do this\n        return\n    }\n    fmt.Fprint(w, \"welcome, admin\")\n}\n\nfunc main() {\n    for _, token := range &#91;]string{\"\", \"user-token\", \"admin-token\"} {\n        req := httptest.NewRequest(http.MethodGet, \"\/admin\", nil)\n        req.Header.Set(\"Authorization\", token)\n        rec := httptest.NewRecorder()\n        adminOnly(rec, req)\n        fmt.Printf(\"token=%q status=%d\\n\", token, rec.Code)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>token=\"\" status=401\ntoken=\"user-token\" status=403\ntoken=\"admin-token\" status=200<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q100. What is authorization?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Authorization decides what an authenticated user is allowed to access or do. It always happens after authentication.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a user first logs in with a username and password. Then the system checks questions like these.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Can this user open the dashboard?<\/li>\n\n\n\n<li>Is this user allowed to delete a record?<\/li>\n\n\n\n<li>Can this user upload a file?<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, you usually check roles or permissions in middleware before the handler runs. If the check fails, you return 403 Forbidden.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q101. What is Gorilla Mux, and how does routing work in Gin?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Gorilla Mux and Gin are separate routers. You do not use Gorilla Mux inside Gin. You pick one of them for a project.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Library<\/th><th>Package<\/th><th>What it is<\/th><\/tr><\/thead><tbody><tr><td>Gorilla Mux<\/td><td><code>github.com\/gorilla\/mux<\/code><\/td><td>A router that plugs into <code>net\/http<\/code><\/td><\/tr><tr><td>Gin<\/td><td><code>github.com\/gin-gonic\/gin<\/code><\/td><td>A full web framework with its own router<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Gorilla Mux gives <code>net\/http<\/code> extra routing features. These include path variables like <code>\/users\/{id}<\/code>, method matching, query and header matching, and middleware. The project was archived in 2022 but is maintained again since 2023.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is routing with Gorilla Mux. It needs the module, so it does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net\/http\"\n\n    \"github.com\/gorilla\/mux\"\n)\n\nfunc main() {\n    r := mux.NewRouter()\n    r.HandleFunc(\"\/users\/{id}\", func(w http.ResponseWriter, r *http.Request) {\n        id := mux.Vars(r)&#91;\"id\"] \/\/ read the path variable\n        fmt.Fprintf(w, \"User ID: %s\", id)\n    }).Methods(http.MethodGet)\n\n    log.Fatal(http.ListenAndServe(\":8080\", r))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Gin has its own router, built on a fast radix tree. You register a route with a method function like <code>r.GET<\/code>, and path parameters use a colon, such as <code>\/users\/:id<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"github.com\/gin-gonic\/gin\"\n\nfunc main() {\n    r := gin.Default()\n    r.GET(\"\/users\/:id\", func(c *gin.Context) {\n        c.JSON(200, gin.H{\"user_id\": c.Param(\"id\")})\n    })\n    r.Run(\":8080\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.22, the standard <code>net\/http<\/code> mux also supports methods and path variables, such as <code>\"GET \/users\/{id}\"<\/code>. So for many small APIs you need neither library.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q102. What is Gin used for?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Gin is a fast web framework for Go. It gives you a router, middleware, JSON handling, request binding and validation in one package. It is built on top of <code>net\/http<\/code>, so it works with standard Go handlers and tools.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"github.com\/gin-gonic\/gin\"\n\nfunc main() {\n    r := gin.Default() \/\/ includes logger and panic recovery middleware\n\n    r.GET(\"\/users\/:id\", func(c *gin.Context) {\n        id := c.Param(\"id\")\n        c.JSON(200, gin.H{\"user_id\": id})\n    })\n\n    r.Run(\":8080\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how its routing style compares with Gorilla Mux.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Gorilla Mux<\/th><th>Gin<\/th><\/tr><\/thead><tbody><tr><td>Path parameter<\/td><td><code>{id}<\/code><\/td><td><code>:id<\/code><\/td><\/tr><tr><td>Response<\/td><td>Manual, with <code>fmt.Fprintf<\/code> or <code>json.NewEncoder<\/code><\/td><td>Helpers like <code>c.JSON<\/code> and <code>c.String<\/code><\/td><\/tr><tr><td>Speed<\/td><td>Fast enough for most apps<\/td><td>Very fast router<\/td><\/tr><tr><td>Scope<\/td><td>Router only<\/td><td>Router, middleware, binding and validation<\/td><\/tr><tr><td>Learning curve<\/td><td>Simple<\/td><td>Moderate<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Use Gorilla Mux when<\/th><th>Use Gin when<\/th><\/tr><\/thead><tbody><tr><td>You want a simple router<\/td><td>You want a full web backend<\/td><\/tr><tr><td>You prefer plain <code>net\/http<\/code><\/td><td>You need fast JSON APIs<\/td><\/tr><tr><td>The project is small<\/td><td>You build a larger REST API<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q103. What is the difference between query parameters and path parameters?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Path parameters are part of the route itself, such as <code>10<\/code> in <code>\/users\/10<\/code>. They identify one specific resource, so they are required. Query parameters come after the <code>?<\/code>, such as <code>\/users?role=admin&amp;page=2<\/code>. They are optional and are used for filters, search, sorting and pagination.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Query parameters<\/th><th>Path parameters<\/th><\/tr><\/thead><tbody><tr><td>Place in URL<\/td><td>After <code>?<\/code><\/td><td>Inside the route<\/td><\/tr><tr><td>Required<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Purpose<\/td><td>Filters, search, optional inputs<\/td><td>Identify a specific resource<\/td><\/tr><tr><td>Example<\/td><td><code>\/users?role=admin<\/code><\/td><td><code>\/users\/10<\/code><\/td><\/tr><tr><td>Read in Gin<\/td><td><code>c.Query(\"role\")<\/code><\/td><td><code>c.Param(\"id\")<\/code><\/td><\/tr><tr><td>Read in <code>net\/http<\/code><\/td><td><code>r.URL.Query().Get(\"role\")<\/code><\/td><td><code>r.PathValue(\"id\")<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is both kinds read with the standard library.<\/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\nfunc main() {\n    mux := http.NewServeMux()\n    mux.HandleFunc(\"GET \/users\/{id}\", func(w http.ResponseWriter, r *http.Request) {\n        id := r.PathValue(\"id\")               \/\/ path parameter\n        fields := r.URL.Query().Get(\"fields\") \/\/ query parameter\n        fmt.Fprintf(w, \"id=%s fields=%s\", id, fields)\n    })\n\n    req := httptest.NewRequest(http.MethodGet, \"\/users\/10?fields=name\", nil)\n    rec := httptest.NewRecorder()\n    mux.ServeHTTP(rec, req)\n    fmt.Println(rec.Body.String())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>id=10 fields=name<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q104. How do you manage a cache in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a single service instance, an in-memory cache is the simplest choice. It gives very fast reads, but the data is lost on restart. When you run many instances, use a shared cache like Redis so all of them see the same data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small, safe in-memory cache. A <code>sync.RWMutex<\/code> lets many readers in at once, but only one writer.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Cache is a map protected by a read-write mutex.\ntype Cache struct {\n    mu    sync.RWMutex\n    items map&#91;string]string\n}\n\nfunc NewCache() *Cache {\n    return &amp;Cache{items: make(map&#91;string]string)}\n}\n\nfunc (c *Cache) Get(key string) (string, bool) {\n    c.mu.RLock()\n    defer c.mu.RUnlock()\n    value, ok := c.items&#91;key]\n    return value, ok\n}\n\nfunc (c *Cache) Set(key, value string) {\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    c.items&#91;key] = value\n}\n\nfunc main() {\n    cache := NewCache()\n    cache.Set(\"user:1\", \"Asha\")\n\n    if name, ok := cache.Get(\"user:1\"); ok {\n        fmt.Println(\"hit:\", name)\n    }\n    if _, ok := cache.Get(\"user:2\"); !ok {\n        fmt.Println(\"miss: load from database\")\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>hit: Asha\nmiss: load from database<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some good caching rules.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Cache data that is read often and changes rarely.<\/li>\n\n\n\n<li>Set an expiry time (TTL) and a size limit, so the cache cannot grow forever.<\/li>\n\n\n\n<li>Never cache auth-sensitive data blindly, because a user could see another user&#8217;s data.<\/li>\n\n\n\n<li>Measure the hit ratio to check the cache really helps.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q105. How do you do authentication and authorization in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Authentication answers &#8220;Who are you?&#8221;, for example with a login and a token. Authorization answers &#8220;What are you allowed to do?&#8221;, for example with roles and permissions. Authentication always comes first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are four common ways to authenticate in Go.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Basic Auth, with a username and password in a header. It is simple, but rarely used in production.<\/li>\n\n\n\n<li>Sessions, with a session ID in a cookie. This is typical for server-rendered web apps.<\/li>\n\n\n\n<li>Tokens, such as JWT. This is the most common choice for APIs.<\/li>\n\n\n\n<li>Third-party login with OAuth 2.0 and OpenID Connect, for example Google or GitHub.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">A JWT flow works like this. The user logs in, you verify the password with bcrypt and you create a signed JWT. Then the client sends the JWT on every request, and middleware validates it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how you create and check a token with <code>github.com\/golang-jwt\/jwt\/v5<\/code>. It needs that module, so it does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var secret = &#91;]byte(os.Getenv(\"JWT_SECRET\"))\n\n\/\/ createToken signs a short-lived token with the user's ID and role.\nfunc createToken(userID, role string) (string, error) {\n    claims := jwt.MapClaims{\n        \"sub\":  userID,\n        \"role\": role,\n        \"exp\":  time.Now().Add(15 * time.Minute).Unix(),\n    }\n    return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)\n}\n\n\/\/ parseToken checks the signature, the algorithm and the expiry.\nfunc parseToken(tokenString string) (jwt.MapClaims, error) {\n    token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {\n        return secret, nil\n    }, jwt.WithValidMethods(&#91;]string{\"HS256\"}))\n    if err != nil {\n        return nil, err\n    }\n    return token.Claims.(jwt.MapClaims), nil\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then a second middleware checks the role from the claims, which is authorization. It returns 403 if the role is not allowed.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Scenario<\/th><th>Common solution<\/th><\/tr><\/thead><tbody><tr><td>Simple API<\/td><td>JWT<\/td><\/tr><tr><td>Microservices<\/td><td>JWT, with Redis for revoked tokens<\/td><\/tr><tr><td>Enterprise<\/td><td>OAuth 2.0 or OpenID Connect with Keycloak<\/td><\/tr><tr><td>Mobile app<\/td><td>Short-lived JWT with a refresh token<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In short, authenticate with a login and JWT, then authorize with role middleware. Also protect routes with middleware, hash passwords with bcrypt and always use HTTPS.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q106. What is the difference between Fiber and Gin?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both are popular Go web frameworks, but they sit on different HTTP engines. Fiber is built on <code>fasthttp<\/code>, while Gin is built on the standard <code>net\/http<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Fiber<\/th><th>Gin<\/th><\/tr><\/thead><tbody><tr><td>HTTP engine<\/td><td><code>fasthttp<\/code><\/td><td><code>net\/http<\/code><\/td><\/tr><tr><td>Raw speed<\/td><td>Very high in benchmarks<\/td><td>High<\/td><\/tr><tr><td>Memory use<\/td><td>Low<\/td><td>Low<\/td><\/tr><tr><td>Style<\/td><td>Similar to Express.js<\/td><td>Standard Go style<\/td><\/tr><tr><td>Works with <code>net\/http<\/code> middleware<\/td><td>Only through adapters<\/td><td>Yes<\/td><\/tr><tr><td>HTTP\/2<\/td><td>Not supported by <code>fasthttp<\/code><\/td><td>Supported<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Choose Fiber when you want top raw speed for small microservices or you like Express.js syntax. Choose Gin when you want standard Go behaviour, wide library support and a long production record.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In real systems, the framework is rarely the bottleneck. Database queries, caching and architecture matter much more than benchmark numbers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q107. Which command installs Fiber in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fiber v3 is the current major version, so you install it with this command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go get github.com\/gofiber\/fiber\/v3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Fiber v3 needs a recent Go version, so check its README for the minimum. Older projects still use v2, which you install with <code>go get github.com\/gofiber\/fiber\/v2<\/code>. The import path must match the version you installed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a small Fiber v3 app. In v3 the handler takes <code>fiber.Ctx<\/code> (an interface), not <code>*fiber.Ctx<\/code> like in v2.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"log\"\n\n    \"github.com\/gofiber\/fiber\/v3\"\n)\n\nfunc main() {\n    app := fiber.New()\n\n    app.Get(\"\/\", func(c fiber.Ctx) error {\n        return c.SendString(\"Hello, Fiber\")\n    })\n\n    log.Fatal(app.Listen(\":3000\"))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q108. What are the parts of a JWT?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A JWT has three parts joined by dots, <code>header.payload.signature<\/code>. Each part is Base64URL encoded.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The header holds metadata about the token.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>alg<\/code> is the signing algorithm, for example HS256 or RS256.<\/li>\n\n\n\n<li><code>typ<\/code> is the token type, usually <code>JWT<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The payload holds the claims, which is the data you send. Claims come in three types, registered, public and private. Here are the registered (standard) claims.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>iss<\/code> (issuer) is who created the token.<\/li>\n\n\n\n<li><code>sub<\/code> (subject) is the user ID.<\/li>\n\n\n\n<li><code>aud<\/code> (audience) is who the token is meant for.<\/li>\n\n\n\n<li><code>exp<\/code> (expiration time) is when the token expires.<\/li>\n\n\n\n<li><code>nbf<\/code> (not before) is when the token becomes valid.<\/li>\n\n\n\n<li><code>iat<\/code> (issued at) is when the token was created.<\/li>\n\n\n\n<li><code>jti<\/code> (JWT ID) is a unique ID for the token.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A signature proves the token was not changed. The server signs the header and payload with a secret or private key, then checks it on every request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The payload is only encoded, not encrypted. So anyone can read it, and you must never put passwords in it. This program decodes a JWT payload with the standard library.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"encoding\/base64\"\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    \/\/ Build a sample token. The signature part is fake here.\n    header := base64.RawURLEncoding.EncodeToString(&#91;]byte(`{\"alg\":\"HS256\",\"typ\":\"JWT\"}`))\n    payload := base64.RawURLEncoding.EncodeToString(&#91;]byte(`{\"sub\":\"42\",\"role\":\"admin\"}`))\n    token := header + \".\" + payload + \".signature\"\n\n    parts := strings.Split(token, \".\")\n    fmt.Println(\"parts:\", len(parts))\n\n    decoded, err := base64.RawURLEncoding.DecodeString(parts&#91;1])\n    if err != nil {\n        fmt.Println(\"bad payload:\", err)\n        return\n    }\n    fmt.Println(\"payload:\", string(decoded))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>parts: 3\npayload: {\"sub\":\"42\",\"role\":\"admin\"}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q109. What is GraphQL?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">GraphQL is a query language for APIs. Instead of many REST endpoints, it usually exposes a single endpoint, such as <code>\/graphql<\/code>. The client asks for exactly the fields it needs, so it avoids getting too much or too little data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>query {\n  user(id: \"42\") {\n    name\n    orders { id total }\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each field in the schema is backed by a resolver function. A resolver can read a database or call another service. Then the GraphQL engine runs the resolvers, often in parallel, and merges the results into one JSON response.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, the most popular library is <code>github.com\/99designs\/gqlgen<\/code>. It generates type-safe Go code from your schema.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q110. What is a stateless API?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A stateless API is one where each request carries all the information needed to handle it. The server does not keep any client session between requests. For example, every request sends its own JWT in the <code>Authorization<\/code> header.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is why stateless APIs matter.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Any server can handle any request, so you can scale out by adding servers.<\/li>\n\n\n\n<li>If one server fails, another can take over with no lost session.<\/li>\n\n\n\n<li>There is no session lookup, so requests stay fast.<\/li>\n\n\n\n<li>It fits microservices and load balancers well.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Your data still lives in a database. &#8220;Stateless&#8221; only means the server does not remember the client between calls.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q111. What is routing in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Routing maps an incoming HTTP request (method plus URL path) to the handler function that should process it. Here is how it works.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The client sends a request with a method and a URL.<\/li>\n\n\n\n<li>The router matches the path and method.<\/li>\n\n\n\n<li>It calls the matching handler.<\/li>\n\n\n\n<li>The handler writes the response.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">There are three common kinds of routes. A static route has a fixed path, such as <code>\/health<\/code>. A dynamic route has a variable part, such as <code>\/users\/{id}<\/code>. Query parameters add optional inputs, such as <code>\/users?page=2<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.22, the standard <code>http.ServeMux<\/code> handles all of these.<\/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\nfunc main() {\n    mux := http.NewServeMux()\n\n    \/\/ Static route\n    mux.HandleFunc(\"GET \/health\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprint(w, \"ok\")\n    })\n    \/\/ Dynamic route with a path variable\n    mux.HandleFunc(\"GET \/users\/{id}\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"user %s\", r.PathValue(\"id\"))\n    })\n    \/\/ Query parameters on a static path\n    mux.HandleFunc(\"GET \/users\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"users page %s\", r.URL.Query().Get(\"page\"))\n    })\n\n    for _, path := range &#91;]string{\"\/health\", \"\/users\/7\", \"\/users?page=2\"} {\n        rec := httptest.NewRecorder()\n        mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))\n        fmt.Println(path, \"-&gt;\", rec.Body.String())\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>\/health -&gt; ok\n\/users\/7 -&gt; user 7\n\/users?page=2 -&gt; users page 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q112. What is the difference between http.HandleFunc and an HTTP method?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They are different things. <code>http.HandleFunc<\/code> registers a route, mapping a URL pattern to a handler function. An HTTP method, like GET, POST, PUT or DELETE, is the type of operation the client wants on that route.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Concept<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td><code>http.HandleFunc<\/code><\/td><td>Registers a route (pattern to handler) in the <code>net\/http<\/code> package<\/td><\/tr><tr><td>HTTP method<\/td><td>The type of request, such as GET, POST, PUT or DELETE<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Before Go 1.22, <code>HandleFunc<\/code> matched only the path. So you had to check <code>r.Method<\/code> by hand inside every handler. Since Go 1.22, you can put the method in the pattern itself, such as <code>\"POST \/users\"<\/code>. Then the mux returns 405 Method Not Allowed for other methods.<\/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\nfunc main() {\n    mux := http.NewServeMux()\n    mux.HandleFunc(\"POST \/users\", func(w http.ResponseWriter, r *http.Request) {\n        w.WriteHeader(http.StatusCreated)\n        fmt.Fprint(w, \"user created\")\n    })\n\n    for _, method := range &#91;]string{http.MethodPost, http.MethodGet} {\n        rec := httptest.NewRecorder()\n        mux.ServeHTTP(rec, httptest.NewRequest(method, \"\/users\", nil))\n        fmt.Println(method, rec.Code)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>POST 201\nGET 405<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Frameworks like Gin and Fiber give you the same idea with methods like <code>r.GET<\/code> and <code>app.Post<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q113. What is a connection pool in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A connection pool is a set of open connections that your app reuses, instead of opening a new one for every request. Opening a database connection is slow, because it needs a network round trip, authentication and memory. So reusing connections makes your app much faster.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without a pool, every request opens a connection, runs a query and closes it. With a pool, connections stay open and requests borrow one and give it back.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go&#8217;s <code>database\/sql<\/code> package manages a pool for you. So <code>sql.Open<\/code> returns a pool, not a single connection, and you usually create it once and share it.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Setting<\/th><th>What it does<\/th><\/tr><\/thead><tbody><tr><td><code>SetMaxOpenConns(20)<\/code><\/td><td>At most 20 connections open at once<\/td><\/tr><tr><td><code>SetMaxIdleConns(5)<\/code><\/td><td>Keeps up to 5 idle connections ready<\/td><\/tr><tr><td><code>SetConnMaxLifetime(time.Hour)<\/code><\/td><td>Replaces a connection after it has been open 1 hour<\/td><\/tr><tr><td><code>SetConnMaxIdleTime(10 * time.Minute)<\/code><\/td><td>Closes connections idle for 10 minutes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example with the pgx PostgreSQL driver. It needs a driver module and a database, so it does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"database\/sql\"\n    \"log\"\n    \"os\"\n    \"time\"\n\n    _ \"github.com\/jackc\/pgx\/v5\/stdlib\" \/\/ registers the \"pgx\" driver\n)\n\nfunc main() {\n    \/\/ Read the connection string from the environment, not from code.\n    db, err := sql.Open(\"pgx\", os.Getenv(\"DATABASE_URL\"))\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer db.Close()\n\n    db.SetMaxOpenConns(20)\n    db.SetMaxIdleConns(5)\n    db.SetConnMaxLifetime(time.Hour)\n    db.SetConnMaxIdleTime(10 * time.Minute)\n\n    \/\/ sql.Open does not connect, so Ping checks the database is reachable.\n    if err := db.Ping(); err != nil {\n        log.Fatal(err)\n    }\n    log.Println(\"database connected\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the benefits of a pool.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Requests are faster, because connections are reused.<\/li>\n\n\n\n<li>There is less overhead from opening and closing connections.<\/li>\n\n\n\n<li>It limits how many connections hit the database at once.<\/li>\n\n\n\n<li>It helps the app scale under high traffic without exhausting the database.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q114. If you store a password in a properties file, how do you read it, and should you print it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can read it, but you should never print or log it. Logs are copied to many systems and seen by many people. So a printed password is a leaked password.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the safe approach.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep secrets out of your code and out of Git. Add files like <code>.env<\/code> to <code>.gitignore<\/code>.<\/li>\n\n\n\n<li>In production, read secrets from environment variables or a secret manager, such as AWS Secrets Manager, HashiCorp Vault or Kubernetes Secrets.<\/li>\n\n\n\n<li>To check a secret loaded, print only whether it is set, or a masked value.<\/li>\n\n\n\n<li>Fail early with a clear message if a required secret is missing, but do not include its value.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a program that reads a properties-style config and checks the password without showing it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ parseProperties reads key=value lines and skips comments and blanks.\nfunc parseProperties(text string) map&#91;string]string {\n    props := make(map&#91;string]string)\n    scanner := bufio.NewScanner(strings.NewReader(text))\n    for scanner.Scan() {\n        line := strings.TrimSpace(scanner.Text())\n        if line == \"\" || strings.HasPrefix(line, \"#\") {\n            continue\n        }\n        key, value, found := strings.Cut(line, \"=\")\n        if found {\n            props&#91;strings.TrimSpace(key)] = strings.TrimSpace(value)\n        }\n    }\n    return props\n}\n\n\/\/ mask hides a secret, so logs never show the real value.\nfunc mask(secret string) string {\n    if secret == \"\" {\n        return \"(not set)\"\n    }\n    return \"********\"\n}\n\nfunc main() {\n    \/\/ In a real app this text comes from a file such as app.properties.\n    config := \"# database settings\\ndb.user=appuser\\ndb.password=S3cret!Pass\\n\"\n    props := parseProperties(config)\n\n    fmt.Println(\"db.user:\", props&#91;\"db.user\"])\n    fmt.Println(\"db.password:\", mask(props&#91;\"db.password\"]))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>db.user: appuser\ndb.password: ********<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Many projects use a <code>.env<\/code> file with <code>github.com\/joho\/godotenv<\/code> and then call <code>os.Getenv<\/code>. That module is external, so this snippet does not run here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if err := godotenv.Load(); err != nil {\n    log.Println(\"no .env file, using real environment variables\")\n}\n\npassword := os.Getenv(\"DB_PASSWORD\")\nif password == \"\" {\n    log.Fatal(\"DB_PASSWORD is not set\")\n}\nlog.Println(\"DB_PASSWORD loaded\") \/\/ never log the value itself<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Golang Questions and Answers on Microservices, System Design and Tools<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Golang questions and answers cover how Go fits into real systems, such as microservices, messaging, scaling and the tools around your code. Many topics are not Go-only, so each answer explains the idea and then shows where Go helps.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q115. What are the common Go design principles?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go is built around a few simple ideas. If you follow them, your code looks like other Go code and is easy to read.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Simplicity.<\/strong> Write plain, clear code. Go has a small language on purpose.<\/li>\n\n\n\n<li><strong>Composition over inheritance.<\/strong> Go has no classes or inheritance. You build types from smaller structs (embedding) and small interfaces.<\/li>\n\n\n\n<li><strong>Explicit error handling.<\/strong> Functions return an <code>error<\/code> value, and you check it with <code>if err != nil<\/code>.<\/li>\n\n\n\n<li><strong>Concurrency first.<\/strong> Goroutines and channels make concurrent code a normal part of the design.<\/li>\n\n\n\n<li><strong>Small interfaces.<\/strong> Interfaces like <code>io.Reader<\/code> have one or two methods, so many types can satisfy them.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q116. What is a design pattern in Golang?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A design pattern is a reusable solution to a common software problem. Patterns come from general software engineering, so they are not specific to Go. However, Go implements them in its own simple style, with structs, interfaces, functions and channels instead of classes.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Category<\/th><th>Purpose<\/th><th>Common patterns<\/th><\/tr><\/thead><tbody><tr><td>Creational<\/td><td>Create values<\/td><td>Singleton, Factory, Builder, Functional Options<\/td><\/tr><tr><td>Structural<\/td><td>Combine types<\/td><td>Adapter, Decorator, Facade, Proxy<\/td><\/tr><tr><td>Behavioural<\/td><td>Communication between parts<\/td><td>Strategy, Observer, Command, State<\/td><\/tr><tr><td>Concurrency (Go style)<\/td><td>Run work concurrently<\/td><td>Worker Pool, Pipeline, Fan-in and Fan-out<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The program below shows three patterns together. <code>sync.Once<\/code> gives a singleton, a function returns a type by name (factory), and an interface lets you swap payment methods at runtime (strategy).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Singleton: one shared Database value, created only once.\ntype Database struct{ name string }\n\nvar (\n    once     sync.Once\n    instance *Database\n)\n\nfunc GetDatabase() *Database {\n    once.Do(func() {\n        fmt.Println(\"creating database connection\")\n        instance = &amp;Database{name: \"main-db\"}\n    })\n    return instance\n}\n\n\/\/ Factory: return a Shape based on a string.\ntype Shape interface{ Draw() string }\n\ntype Circle struct{}\ntype Square struct{}\n\nfunc (Circle) Draw() string { return \"drawing a circle\" }\nfunc (Square) Draw() string { return \"drawing a square\" }\n\nfunc NewShape(kind string) Shape {\n    switch kind {\n    case \"circle\":\n        return Circle{}\n    case \"square\":\n        return Square{}\n    }\n    return nil\n}\n\n\/\/ Strategy: pick the payment method at runtime.\ntype PaymentStrategy interface{ Pay(amount float64) string }\n\ntype CreditCard struct{}\ntype PayPal struct{}\n\nfunc (CreditCard) Pay(amount float64) string { return fmt.Sprintf(\"paid %.2f with credit card\", amount) }\nfunc (PayPal) Pay(amount float64) string     { return fmt.Sprintf(\"paid %.2f with PayPal\", amount) }\n\nfunc main() {\n    db1 := GetDatabase()\n    db2 := GetDatabase()\n    fmt.Println(\"same instance:\", db1 == db2)\n\n    fmt.Println(NewShape(\"circle\").Draw())\n    fmt.Println(NewShape(\"square\").Draw())\n\n    for _, method := range &#91;]PaymentStrategy{CreditCard{}, PayPal{}} {\n        fmt.Println(method.Pay(99.5))\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>creating database connection\nsame instance: true\ndrawing a circle\ndrawing a square\npaid 99.50 with credit card\npaid 99.50 with PayPal<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use a pattern when the same problem keeps coming back. But do not force patterns into small programs, because Go prefers the simplest code that works.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q117. How do you consider all factors, like memory management and the database, when you design a new Go project?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Start with the big decisions, then work down to the details. Here is a checklist you can follow.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Architecture.<\/strong> Choose a monolith, a modular monolith or microservices. Clean or hexagonal architecture keeps business logic apart from HTTP and database code.<\/li>\n\n\n\n<li><strong>API contracts.<\/strong> Use gRPC for fast internal calls and REST with JSON for public APIs. Write the OpenAPI or protobuf spec on day one.<\/li>\n\n\n\n<li><strong>Concurrency.<\/strong> The <code>net\/http<\/code> server already runs each request in its own goroutine. Use worker pools for heavy jobs, and pass <code>context.Context<\/code> everywhere for timeouts and cancellation.<\/li>\n\n\n\n<li><strong>Data storage.<\/strong> Pick the database that fits the data, as the table shows.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Need<\/th><th>Database choice<\/th><\/tr><\/thead><tbody><tr><td>Strict ACID, complex joins<\/td><td>PostgreSQL, MySQL<\/td><\/tr><tr><td>Flexible schema, horizontal scale<\/td><td>MongoDB, Couchbase<\/td><\/tr><tr><td>Fast cache, data with expiry (TTL)<\/td><td>Redis<\/td><\/tr><tr><td>Analytics<\/td><td>ClickHouse, BigQuery<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For memory and performance, measure first and optimise second. Go has a concurrent garbage collector, so you rarely manage memory by hand.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Action<\/th><th>Tool or detail<\/th><\/tr><\/thead><tbody><tr><td>Avoid needless allocations<\/td><td>Reuse buffers with <code>sync.Pool<\/code>, stream large data with <code>io.Reader<\/code><\/td><\/tr><tr><td>Understand escape analysis<\/td><td><code>go build -gcflags=\"-m\"<\/code> shows stack and heap decisions<\/td><\/tr><tr><td>Profile early<\/td><td><code>pprof<\/code>, <code>go tool trace<\/code>, <code>allocs\/op<\/code> in benchmarks<\/td><\/tr><tr><td>Tune the GC (rarely)<\/td><td><code>GOGC<\/code>, <code>GOMEMLIMIT<\/code>, only after measuring<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For the database, <code>database\/sql<\/code> already has a connection pool. So set <code>SetMaxOpenConns<\/code>, <code>SetMaxIdleConns<\/code> and <code>SetConnMaxLifetime<\/code>. Use parameterised queries (or tools like sqlc, GORM, bun) to stop SQL injection. Then manage schema changes with migration tools such as golang-migrate or goose, and give every query a context with a timeout.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Area<\/th><th>Recommendation<\/th><\/tr><\/thead><tbody><tr><td>Errors<\/td><td>Libraries return errors and do not panic. Wrap with <code>fmt.Errorf(\"...: %w\", err)<\/code><\/td><\/tr><tr><td>Logging<\/td><td>Structured logs with the standard <code>log\/slog<\/code> package (or zap, zerolog)<\/td><\/tr><tr><td>Metrics and tracing<\/td><td>Prometheus client, OpenTelemetry<\/td><\/tr><tr><td>Health checks<\/td><td><code>\/healthz<\/code> and <code>\/readyz<\/code> endpoints, plus a DB ping<\/td><\/tr><tr><td>Testing<\/td><td>Table-driven tests, testcontainers-go, <code>go test -bench<\/code>, <code>go test -fuzz<\/code><\/td><\/tr><tr><td>CI<\/td><td><code>go vet<\/code>, golangci-lint, <code>govulncheck<\/code>, tests, then build the image<\/td><\/tr><tr><td>Containers<\/td><td>Multi-stage Dockerfile with a distroless or scratch image<\/td><\/tr><tr><td>Config and secrets<\/td><td>Environment variables, Vault or AWS Secrets Manager, never inside images<\/td><\/tr><tr><td>Security<\/td><td>TLS everywhere, JWT or OAuth2 for users, mTLS for internal gRPC, gosec<\/td><\/tr><tr><td>Shutdown<\/td><td><code>http.Server.Shutdown<\/code> with <code>signal.NotifyContext<\/code><\/td><\/tr><tr><td>Back-pressure<\/td><td>Buffered channels, worker pools, <code>golang.org\/x\/time\/rate<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, a common folder layout looks like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cmd\/            entry points (main packages)\ninternal\/\n    app\/        business logic, service layer\n    db\/         SQL queries, repository layer\n    transport\/\n        http\/\n        grpc\/\npkg\/            reusable libraries (only if others import them)\nconfigs\/        default YAML or JSON config\nscripts\/        CI and developer helpers\ndeploy\/         Helm charts, Terraform<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q118. What is gRPC in Golang?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">gRPC is a fast, open-source Remote Procedure Call (RPC) framework created by Google. It lets one service call a function on another service as if it were local. Services can be written in different languages, for example Go, Java or Python.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>HTTP\/2.<\/strong> It supports multiplexing and streaming, so it is faster than plain HTTP\/1.1.<\/li>\n\n\n\n<li><strong>Protocol Buffers.<\/strong> You define messages and services in a <code>.proto<\/code> file. Protobuf data is binary and compact, so it is smaller and faster than JSON.<\/li>\n\n\n\n<li><strong>Code generation.<\/strong> <code>protoc<\/code> with the <code>protoc-gen-go<\/code> and <code>protoc-gen-go-grpc<\/code> plugins creates Go server and client code for you.<\/li>\n\n\n\n<li><strong>Four call types.<\/strong> Unary (one request, one response), server streaming, client streaming and bidirectional streaming.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use gRPC for low-latency, internal microservice calls. For public browser APIs, REST with JSON is usually simpler. Here is a small <code>.proto<\/code> file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>syntax = \"proto3\";\npackage user;\noption go_package = \"example.com\/userpb\";\n\nservice UserService {\n  rpc GetUser(GetUserRequest) returns (User);\n}\n\nmessage GetUserRequest { int64 id = 1; }\nmessage User { int64 id = 1; string name = 2; }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then the Go server implements the generated interface. This needs the external module <code>google.golang.org\/grpc<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type server struct {\n    userpb.UnimplementedUserServiceServer\n}\n\nfunc (s *server) GetUser(ctx context.Context, req *userpb.GetUserRequest) (*userpb.User, error) {\n    return &amp;userpb.User{Id: req.Id, Name: \"Asha\"}, nil\n}\n\nfunc main() {\n    lis, err := net.Listen(\"tcp\", \":50051\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    s := grpc.NewServer()\n    userpb.RegisterUserServiceServer(s, &amp;server{})\n    log.Fatal(s.Serve(lis))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q119. What is RabbitMQ?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">RabbitMQ is an open-source message broker. It lets services talk to each other by sending and receiving messages asynchronously, so they do not call each other directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It works in three steps. First, a producer sends a message to an exchange. Next, the exchange routes it into one or more queues. Then a consumer reads the message from the queue and acknowledges it when the work is done.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It decouples services and handles background work.<\/li>\n\n\n\n<li>It buffers messages when consumers are slow.<\/li>\n\n\n\n<li>Durable queues and acknowledgements mean messages are not lost when a consumer is down.<\/li>\n\n\n\n<li>It supports patterns such as work queues, publish and subscribe, routing and topics.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Common uses are sending emails in the background, image or video processing, and notifications. In Go, the official client is <code>github.com\/rabbitmq\/amqp091-go<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q120. What is Kafka and why is it used?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Apache Kafka is an open-source, distributed event streaming platform. It handles real-time data streams at a very large scale. Think of it as a durable log that many services can write to and read from.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Producers<\/strong> write messages (events) to a <strong>topic<\/strong>.<\/li>\n\n\n\n<li><strong>Brokers<\/strong> are Kafka servers that store the topics.<\/li>\n\n\n\n<li>Each topic is split into <strong>partitions<\/strong>, so many consumers can read in parallel.<\/li>\n\n\n\n<li><strong>Consumers<\/strong> read messages. Consumers in the same <strong>consumer group<\/strong> share the partitions between them.<\/li>\n\n\n\n<li>Kafka keeps messages for a set time, so consumers can replay old events.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Teams use Kafka for real-time streaming of logs, metrics and transactions. It also powers event-driven microservices and moves data between systems, for example MySQL to Kafka to Elasticsearch. Log aggregation and live analytics are other common uses.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Kafka<\/th><th>RabbitMQ<\/th><\/tr><\/thead><tbody><tr><td>Event log, messages kept for replay<\/td><td>Queue, message removed after ack<\/td><\/tr><tr><td>Very high throughput<\/td><td>Flexible routing<\/td><\/tr><tr><td>Good for streams and analytics<\/td><td>Good for task queues<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, popular clients are <code>github.com\/segmentio\/kafka-go<\/code>, <code>github.com\/twmb\/franz-go<\/code> and <code>confluent-kafka-go<\/code>. This short producer uses kafka-go.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>writer := &amp;kafka.Writer{\n    Addr:  kafka.TCP(\"localhost:9092\"),\n    Topic: \"orders\",\n}\ndefer writer.Close()\n\nerr := writer.WriteMessages(context.Background(),\n    kafka.Message{Key: &#91;]byte(\"order-1\"), Value: &#91;]byte(`{\"total\": 250}`)},\n)\nif err != nil {\n    log.Fatal(err)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q121. What are monolithic and microservice applications, and what is the difference between them?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A monolithic application is one unified program. The UI, business logic and data access are built and deployed together, often as a single binary. So it is simple to start, but every change means redeploying the whole app.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A microservice application is split into small, independent services. Each one owns one business function, for example an Order Service, a Payment Service and an Inventory Service. They talk through REST, gRPC or message queues like Kafka and RabbitMQ.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Aspect<\/th><th>Monolithic<\/th><th>Microservices<\/th><\/tr><\/thead><tbody><tr><td>Codebase<\/td><td>One<\/td><td>One per service<\/td><\/tr><tr><td>Deployment<\/td><td>Whole app at once<\/td><td>Each service on its own<\/td><\/tr><tr><td>Scaling<\/td><td>Whole app scales together<\/td><td>Scale only busy services<\/td><\/tr><tr><td>Database<\/td><td>Usually one shared database<\/td><td>Each service owns its data<\/td><\/tr><tr><td>Coupling<\/td><td>Tight<\/td><td>Loose<\/td><\/tr><tr><td>Tech stack<\/td><td>Usually one<\/td><td>Can differ per service<\/td><\/tr><tr><td>Fault isolation<\/td><td>One bug can crash everything<\/td><td>A failure stays in one service<\/td><\/tr><tr><td>Team speed<\/td><td>Slower for large teams<\/td><td>Small teams work in parallel<\/td><\/tr><tr><td>Complexity<\/td><td>Simple to start, hard at large scale<\/td><td>Harder to start (network, monitoring), easier at large scale<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A good rule is to start with a well-structured monolith. Then split out services when you have a clear reason.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q122. What coding practices should you follow in Golang?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Following common Go practices makes your code easy for other Go developers to read. Start with naming.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Item<\/th><th>Convention<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Package<\/td><td>short, lower case, no underscores<\/td><td><code>userauth<\/code><\/td><\/tr><tr><td>Unexported names<\/td><td>camelCase<\/td><td><code>totalCount<\/code>, <code>getUserData()<\/code><\/td><\/tr><tr><td>Exported names<\/td><td>PascalCase<\/td><td><code>GetUser()<\/code><\/td><\/tr><tr><td>Constants<\/td><td>camelCase or PascalCase (not UPPER_SNAKE_CASE)<\/td><td><code>maxRetry<\/code>, <code>DefaultLimit<\/code><\/td><\/tr><tr><td>Acronyms<\/td><td>keep one case<\/td><td><code>userID<\/code>, <code>ServeHTTP<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The old answer suggested UPPER_SNAKE_CASE for constants. However, Go style uses normal camelCase or PascalCase for constants too.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Format with gofmt.<\/strong> Run <code>go fmt .\/...<\/code> or <code>gofmt<\/code>. It uses tabs and aligns your code automatically.<\/li>\n\n\n\n<li><strong>Keep functions small.<\/strong> Split one huge <code>ProcessOrder<\/code> into <code>ValidateOrder<\/code>, <code>SaveOrder<\/code> and <code>SendOrderEmail<\/code>.<\/li>\n\n\n\n<li><strong>Handle every error.<\/strong> Return early instead of nesting, and wrap errors with context using <code>%w<\/code>.<\/li>\n\n\n\n<li><strong>Avoid global state.<\/strong> Pass dependencies in through constructors.<\/li>\n\n\n\n<li><strong>Pass context.<\/strong> Give API and database functions a <code>ctx context.Context<\/code> as the first parameter.<\/li>\n\n\n\n<li><strong>Name packages by purpose.<\/strong> Prefer <code>logger<\/code>, <code>validation<\/code> or <code>repository<\/code> over a catch-all <code>utils<\/code> package.<\/li>\n\n\n\n<li><strong>Write tests.<\/strong> Run <code>go test .\/...<\/code> and use table-driven tests.<\/li>\n\n\n\n<li><strong>Add interfaces only when needed.<\/strong> Define small interfaces where they are used, not &#8220;just in case&#8221;.<\/li>\n\n\n\n<li><strong>Stay concurrency safe.<\/strong> Protect shared data with a mutex or channels, and run <code>go test -race .\/...<\/code>.<\/li>\n\n\n\n<li><strong>Lint.<\/strong> Run <code>go vet<\/code> and a linter like staticcheck or golangci-lint.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here are early return, error wrapping and dependency injection in one snippet.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Service struct {\n    db *sql.DB\n}\n\nfunc NewService(db *sql.DB) *Service { return &amp;Service{db: db} }\n\nfunc (s *Service) GetUser(ctx context.Context, id int) (User, error) {\n    var u User\n    err := s.db.QueryRowContext(ctx, \"SELECT id, name FROM users WHERE id = $1\", id).Scan(&amp;u.ID, &amp;u.Name)\n    if err != nil {\n        return User{}, fmt.Errorf(\"get user %d: %w\", id, err)\n    }\n    return u, nil\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Do<\/th><th>Avoid<\/th><\/tr><\/thead><tbody><tr><td>Use slices for lists<\/td><td>Copying large arrays by value<\/td><\/tr><tr><td>Preallocate with <code>make([]T, 0, n)<\/code> when you know the size<\/td><td>Growing slices one item at a time in hot loops<\/td><\/tr><tr><td>Reuse objects with <code>sync.Pool<\/code> in hot paths<\/td><td>Needless allocations<\/td><\/tr><tr><td>Profile before you switch JSON libraries<\/td><td>Guessing where the slow part is<\/td><\/tr><tr><td>Use goroutines for I\/O work, with limits<\/td><td>Starting unbounded goroutines<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q123. What is the use of SonarQube?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SonarQube is a code quality and security tool. It scans your source code, including Go, and reports problems before they reach production.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Category<\/th><th>Examples<\/th><\/tr><\/thead><tbody><tr><td>Bugs<\/td><td>Nil pointer issues, resource leaks<\/td><\/tr><tr><td>Vulnerabilities<\/td><td>SQL injection, hardcoded credentials<\/td><\/tr><tr><td>Code smells<\/td><td>Duplicated code, long or complex functions<\/td><\/tr><tr><td>Test coverage<\/td><td>How much code your unit tests cover<\/td><\/tr><tr><td>Maintainability<\/td><td>High complexity, unused code<\/td><\/tr><tr><td>Security hotspots<\/td><td>Code that needs a security review<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Teams use it to keep code clean and to find security risks early. It also enforces shared coding standards and tracks technical debt over time. A <strong>quality gate<\/strong> can fail the build when new code breaks the rules.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SonarQube runs inside CI\/CD pipelines such as Jenkins, GitHub Actions, GitLab CI, Azure DevOps and Bitbucket Pipelines. It scans every commit or pull request. For Go, you pass a coverage file to it, as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>go test .\/... -coverprofile=coverage.out\nsonar-scanner -Dsonar.projectKey=my-go-app -Dsonar.go.coverage.reportPaths=coverage.out<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q124. Why use rebase in Git?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use <code>git rebase<\/code> to keep commit history clean and linear. Rebase takes your commits and replays them on top of another branch, as if you wrote them later. So the history reads as one straight line, with no extra merge commits.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>git switch feature\ngit fetch origin\ngit rebase origin\/main          # replay feature commits on top of the latest main\ngit rebase -i HEAD~3            # squash or edit your last 3 commits\ngit push --force-with-lease     # needed after rebasing a pushed branch<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Rebase rewrites commit hashes. So never rebase a shared branch that other people already use. Use <code>git merge<\/code> there instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The old answer also mentioned &#8220;peek&#8221;. This is an informal word, not a Git command. It means looking at something without changing it.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>To peek at<\/th><th>Command<\/th><\/tr><\/thead><tbody><tr><td>Commit history<\/td><td><code>git log --oneline<\/code><\/td><\/tr><tr><td>Working changes<\/td><td><code>git status<\/code>, <code>git diff<\/code><\/td><\/tr><tr><td>One commit<\/td><td><code>git show &lt;commit-hash&gt;<\/code><\/td><\/tr><tr><td>A file on another branch<\/td><td><code>git show main:file.txt<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q125. What is an API gateway?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An API gateway is a single entry point that sits in front of your microservices. It receives client requests and routes each one to the right service. It also handles shared concerns like authentication, rate limiting, caching, logging and load balancing.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Central security.<\/strong> Check tokens once at the gateway, not in every service.<\/li>\n\n\n\n<li><strong>Easier monitoring.<\/strong> All traffic passes one place.<\/li>\n\n\n\n<li><strong>Better scaling.<\/strong> It spreads load and can cache responses.<\/li>\n\n\n\n<li><strong>Cleaner clients.<\/strong> Clients call one URL instead of many services.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Popular gateways include NGINX, Kong, AWS API Gateway, Apigee and Traefik. You can also build a simple one in Go with <code>net\/http\/httputil.ReverseProxy<\/code>. In fact, Traefik itself is written in Go.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q126. How do you stop one microservice from calling another one repeatedly or too many times?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You combine a few protection patterns. Each one solves a different part of the problem.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Circuit breaker (most important).<\/strong> It tracks failures. After too many, it &#8220;opens&#8221; and stops calls for a while, so the failing service can recover. This also prevents cascading failures. Go libraries include <code>sony\/gobreaker<\/code> and <code>failsafe-go<\/code>.<\/li>\n\n\n\n<li><strong>Rate limiting.<\/strong> It caps how many requests per second a service may send or receive. In Go, use <code>golang.org\/x\/time\/rate<\/code>, or set limits in an API gateway or Redis.<\/li>\n\n\n\n<li><strong>Retry with backoff.<\/strong> Retry only temporary errors, wait longer each time, add jitter and set a maximum number of tries.<\/li>\n\n\n\n<li><strong>Timeouts with context.<\/strong> Every outgoing call needs <code>context.WithTimeout<\/code>, so a slow service cannot block you forever.<\/li>\n\n\n\n<li><strong>Caching.<\/strong> If the data rarely changes, keep it in Redis or an in-memory cache, so you do not call the other service again.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This program builds a tiny circuit breaker. After two failures it opens and rejects calls without contacting the service.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nvar ErrOpen = errors.New(\"circuit open: call skipped\")\n\n\/\/ CircuitBreaker stops calls after too many failures in a row.\ntype CircuitBreaker struct {\n    failures    int\n    maxFailures int\n}\n\nfunc (cb *CircuitBreaker) Call(fn func() error) error {\n    if cb.failures &gt;= cb.maxFailures {\n        return ErrOpen \/\/ do not even call the service\n    }\n    if err := fn(); err != nil {\n        cb.failures++\n        return err\n    }\n    cb.failures = 0 \/\/ success resets the count\n    return nil\n}\n\nfunc main() {\n    cb := &amp;CircuitBreaker{maxFailures: 2}\n    callPayment := func() error { return errors.New(\"payment service timeout\") }\n\n    for i := 1; i &lt;= 4; i++ {\n        fmt.Printf(\"call %d: %v\\n\", i, cb.Call(callPayment))\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>call 1: payment service timeout\ncall 2: payment service timeout\ncall 3: circuit open: call skipped\ncall 4: circuit open: call skipped<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A real breaker also has a &#8220;half-open&#8221; state. After a cool-down time, it lets one test call through, and if that succeeds it closes again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q127. What are the common Docker commands?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Docker packages your Go app and its dependencies into a container image. These are the commands you use most.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker --version                    # show the installed version\ndocker pull nginx                   # download an image\ndocker images                       # list local images\ndocker build -t my-go-app .         # build an image from a Dockerfile\ndocker run -d -p 8080:80 nginx      # run in the background, host port 8080 to container port 80\ndocker ps                           # list running containers (add -a for all)\ndocker logs -f &lt;container&gt;          # follow container logs\ndocker exec -it &lt;container&gt; sh      # open a shell inside a container\ndocker stats                        # live CPU and memory usage\ndocker stop &lt;container&gt;             # stop a container\ndocker rm &lt;container&gt;               # remove a stopped container\ndocker compose up -d                # start all services in compose.yaml\ndocker compose down                 # stop and remove them<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The old <code>docker-compose<\/code> tool (with a hyphen) is replaced by the <code>docker compose<\/code> plugin. Also, a multi-stage Dockerfile keeps Go images very small, as shown here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FROM golang:1.27 AS build\nWORKDIR \/src\nCOPY . .\nRUN CGO_ENABLED=0 go build -o \/app .\/cmd\/server\n\nFROM gcr.io\/distroless\/static\nCOPY --from=build \/app \/app\nENTRYPOINT &#91;\"\/app\"]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q128. What is sharding?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sharding splits data into smaller, independent parts called shards. Each shard holds only part of the data, so the system can scale horizontally. For example, 1 million users could be split by ID range into four shards of 250,000 users each.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a request comes in, you first work out which shard holds the key. Then you read or write only that shard.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, sharding is used in two places. At the database level, it spreads data across many servers. Inside one program, it splits a busy map into many smaller maps, each with its own lock. This reduces lock contention, because goroutines working on different shards do not wait for each other.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"hash\/fnv\"\n    \"sync\"\n)\n\nconst numShards = 4\n\ntype shard struct {\n    mu   sync.RWMutex\n    data map&#91;string]string\n}\n\n\/\/ ShardedCache spreads keys over several maps, each with its own lock.\ntype ShardedCache struct {\n    shards &#91;numShards]*shard\n}\n\nfunc NewShardedCache() *ShardedCache {\n    c := &amp;ShardedCache{}\n    for i := range c.shards {\n        c.shards&#91;i] = &amp;shard{data: make(map&#91;string]string)}\n    }\n    return c\n}\n\n\/\/ shardIndex hashes the key so the same key always goes to the same shard.\nfunc shardIndex(key string) int {\n    h := fnv.New32a()\n    h.Write(&#91;]byte(key))\n    return int(h.Sum32() % numShards)\n}\n\nfunc (c *ShardedCache) Set(key, value string) {\n    s := c.shards&#91;shardIndex(key)]\n    s.mu.Lock()\n    s.data&#91;key] = value\n    s.mu.Unlock()\n}\n\nfunc (c *ShardedCache) Get(key string) (string, bool) {\n    s := c.shards&#91;shardIndex(key)]\n    s.mu.RLock()\n    defer s.mu.RUnlock()\n    v, ok := s.data&#91;key]\n    return v, ok\n}\n\nfunc main() {\n    cache := NewShardedCache()\n    var wg sync.WaitGroup\n    for i := 1; i &lt;= 100; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            key := fmt.Sprintf(\"user%d\", i)\n            cache.Set(key, fmt.Sprintf(\"name-%d\", i))\n        }()\n    }\n    wg.Wait()\n\n    v, ok := cache.Get(\"user42\")\n    fmt.Println(v, ok)\n    total := 0\n    for _, s := range cache.shards {\n        total += len(s.data)\n    }\n    fmt.Println(\"total keys:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>name-42 true\ntotal keys: 100<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Across servers, <strong>consistent hashing<\/strong> is common, because it moves only a few keys when you add or remove a shard.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Advantages<\/th><th>Disadvantages<\/th><\/tr><\/thead><tbody><tr><td>Higher concurrency, less lock contention<\/td><td>More complex code<\/td><\/tr><tr><td>Scales across many machines<\/td><td>Every lookup needs a shard calculation<\/td><\/tr><tr><td>Better CPU use<\/td><td>Rebalancing is hard without consistent hashing<\/td><\/tr><tr><td>Spreads load<\/td><td>Cross-shard queries and transactions are harder<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Use sharding when one lock or one database is a real bottleneck, such as in caches, rate limiters or session stores. But avoid it for small data or low concurrency, because the extra complexity is not worth it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q129. What is cherry-pick in Git?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>git cherry-pick<\/code> copies one specific commit from another branch onto your current branch. You get that single change without merging the whole branch. For example, you can move a bug fix from <code>develop<\/code> into a <code>release<\/code> branch.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>git switch release\ngit cherry-pick a1b2c3d             # apply one commit\ngit cherry-pick a1b2c3d e4f5g6h     # apply several commits\ngit cherry-pick --continue          # after you fix a conflict\ngit cherry-pick --abort             # cancel and go back<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The new commit gets a new hash, because it is a copy. So use cherry-pick for small, targeted fixes, not to move large features.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q130. How do you handle API failure?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You plan for failure, because networks and other services will fail sometimes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Timeouts.<\/strong> Give every call a deadline with <code>context.WithTimeout<\/code>.<\/li>\n\n\n\n<li><strong>Retries with backoff.<\/strong> Retry only temporary errors such as timeouts or HTTP 503.<\/li>\n\n\n\n<li><strong>Circuit breaker.<\/strong> Stop calling a service that keeps failing.<\/li>\n\n\n\n<li><strong>Clear error messages.<\/strong> Return correct HTTP status codes and wrap Go errors with <code>%w<\/code>, so the cause is easy to find.<\/li>\n\n\n\n<li><strong>Fallbacks.<\/strong> Serve cached data or a default response when possible.<\/li>\n\n\n\n<li><strong>Logging and monitoring.<\/strong> Log errors with a request ID and track error rates, so you see problems early.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q131. What is a retry mechanism?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A retry mechanism automatically tries an operation again when it fails. It helps with temporary problems such as network glitches, timeouts and an overloaded server. However, do not retry permanent errors like HTTP 400 or a wrong password.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Good retries use <strong>exponential backoff<\/strong>. So each wait is longer than the last, for example 100 ms, 200 ms, then 400 ms. Also add random jitter in real code, set a maximum number of attempts, and only retry operations that are safe to repeat (idempotent).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"time\"\n)\n\n\/\/ retry calls fn up to maxAttempts times, doubling the wait after each failure.\nfunc retry(maxAttempts int, baseDelay time.Duration, fn func() error) error {\n    delay := baseDelay\n    var err error\n    for attempt := 1; attempt &lt;= maxAttempts; attempt++ {\n        if err = fn(); err == nil {\n            return nil\n        }\n        fmt.Printf(\"attempt %d failed: %v, waiting %v\\n\", attempt, err, delay)\n        time.Sleep(delay)\n        delay *= 2\n    }\n    return fmt.Errorf(\"all %d attempts failed: %w\", maxAttempts, err)\n}\n\nfunc main() {\n    calls := 0\n    fetchOrder := func() error {\n        calls++\n        if calls &lt; 3 {\n            return errors.New(\"service unavailable\")\n        }\n        return nil\n    }\n\n    if err := retry(5, 10*time.Millisecond, fetchOrder); err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"success after\", calls, \"calls\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>attempt 1 failed: service unavailable, waiting 10ms\nattempt 2 failed: service unavailable, waiting 20ms\nsuccess after 3 calls<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q132. How do you handle high traffic?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You spread the load, reduce work per request and add capacity when needed.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Load balancing.<\/strong> Spread requests across many app instances.<\/li>\n\n\n\n<li><strong>Caching.<\/strong> Keep hot data in Redis or a CDN, so fewer requests hit the database.<\/li>\n\n\n\n<li><strong>Database indexing.<\/strong> Add indexes for frequent queries, and use read replicas.<\/li>\n\n\n\n<li><strong>Horizontal scaling.<\/strong> Add more instances, often with auto scaling.<\/li>\n\n\n\n<li><strong>Async work.<\/strong> Push slow tasks to a queue like Kafka, RabbitMQ or SQS.<\/li>\n\n\n\n<li><strong>Rate limiting.<\/strong> Protect the system from floods of requests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Go helps here because each request runs in a cheap goroutine. So one Go instance can serve many thousands of concurrent requests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q133. How do you debug production issues?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You rely on the data your system already records, because you cannot attach a debugger in production.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Logs.<\/strong> Use structured logs (for example <code>log\/slog<\/code>) with a request ID, so you can follow one request.<\/li>\n\n\n\n<li><strong>Monitoring and metrics.<\/strong> Watch error rate, latency and resource use in tools like CloudWatch, Prometheus and Grafana.<\/li>\n\n\n\n<li><strong>Tracing.<\/strong> OpenTelemetry shows how a request moves across services and where time is spent.<\/li>\n\n\n\n<li><strong>Profiling.<\/strong> Go&#8217;s <code>net\/http\/pprof<\/code> shows CPU, memory and goroutine profiles from a running service.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Then reproduce the issue in a staging environment, write a test that fails, fix it and deploy the change.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q134. How do you ensure code quality?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use several checks together, and you automate as many as you can.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Unit tests.<\/strong> Write table-driven tests and run <code>go test -race -cover .\/...<\/code>.<\/li>\n\n\n\n<li><strong>Code reviews.<\/strong> Every change gets reviewed by another developer.<\/li>\n\n\n\n<li><strong>Linting.<\/strong> Run <code>gofmt<\/code>, <code>go vet<\/code>, staticcheck or golangci-lint.<\/li>\n\n\n\n<li><strong>Security scans.<\/strong> Use <code>govulncheck<\/code> and tools like SonarQube.<\/li>\n\n\n\n<li><strong>CI pipeline.<\/strong> Run all of these on every pull request, and block the merge when a check fails.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q135. Why is load balancing needed, and how does it work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A load balancer spreads incoming requests across several backend servers. You need one for four reasons.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No single server gets overloaded.<\/li>\n\n\n\n<li>Response time improves.<\/li>\n\n\n\n<li>You get high availability, because traffic skips unhealthy servers.<\/li>\n\n\n\n<li>Adding servers lets you handle more traffic.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The flow is simple. First, the client sends a request. Next, the load balancer picks a healthy server. Then it forwards the request and sends the response back.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Algorithm<\/th><th>How it picks a server<\/th><\/tr><\/thead><tbody><tr><td>Round robin<\/td><td>Each server in turn<\/td><\/tr><tr><td>Least connections<\/td><td>Server with the fewest active connections<\/td><\/tr><tr><td>IP hash<\/td><td>Same client IP goes to the same server<\/td><\/tr><tr><td>Weighted<\/td><td>More powerful servers get more traffic<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You can also write a load balancer in Go, because <code>net\/http\/httputil.ReverseProxy<\/code> does the forwarding. This program shows the round robin choice. It uses an atomic counter, so it is safe across goroutines.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\/atomic\"\n)\n\ntype RoundRobin struct {\n    servers &#91;]string\n    next    atomic.Uint64\n}\n\n\/\/ Pick returns the next server in turn.\nfunc (rr *RoundRobin) Pick() string {\n    n := rr.next.Add(1) - 1\n    return rr.servers&#91;n%uint64(len(rr.servers))]\n}\n\nfunc main() {\n    lb := &amp;RoundRobin{servers: &#91;]string{\"app1:8080\", \"app2:8080\", \"app3:8080\"}}\n    for req := 1; req &lt;= 5; req++ {\n        fmt.Printf(\"request %d -&gt; %s\\n\", req, lb.Pick())\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>request 1 -&gt; app1:8080\nrequest 2 -&gt; app2:8080\nrequest 3 -&gt; app3:8080\nrequest 4 -&gt; app1:8080\nrequest 5 -&gt; app2:8080<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q136. How do you design a high-scale, low-latency system?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You remove slow work from the request path and scale out instead of up.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Caching.<\/strong> Redis or in-memory caches answer hot reads quickly.<\/li>\n\n\n\n<li><strong>CDN.<\/strong> Serve static files and images close to users.<\/li>\n\n\n\n<li><strong>Load balancing and horizontal scaling.<\/strong> Run many stateless instances behind a load balancer.<\/li>\n\n\n\n<li><strong>Async processing.<\/strong> Send slow work to Kafka or a queue and return quickly.<\/li>\n\n\n\n<li><strong>Database design.<\/strong> Add indexes, read replicas and, at very large scale, sharding.<\/li>\n\n\n\n<li><strong>Efficient calls.<\/strong> Use gRPC, connection pooling and timeouts between services.<\/li>\n\n\n\n<li><strong>Measure.<\/strong> Track p95 and p99 latency, not just the average.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Go fits well because it has fast startup, low memory use and cheap goroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q137. If you get 1,000 requests, which Go features and AWS services can you use to handle them?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a short interview answer. Run several instances of the Go app behind an AWS Application Load Balancer. Each HTTP request runs in its own goroutine, so 1,000 concurrent requests are normal for Go. Then add a database connection pool, a Redis cache and a queue for slow work, with auto scaling for traffic spikes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On the Go side, use these tools.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Goroutines.<\/strong> The <code>net\/http<\/code> server already starts one per request.<\/li>\n\n\n\n<li><strong>Worker pool.<\/strong> Limit CPU-heavy background jobs to a fixed number of workers.<\/li>\n\n\n\n<li><strong>Connection pool.<\/strong> Set <code>db.SetMaxOpenConns(100)<\/code> and <code>db.SetMaxIdleConns(20)<\/code>.<\/li>\n\n\n\n<li><strong>Context timeouts.<\/strong> Use <code>context.WithTimeout<\/code>, so no request hangs forever.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This worker pool sends 6 jobs to 3 workers and collects the results in order.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc worker(jobs &lt;-chan int, results &#91;]int, wg *sync.WaitGroup) {\n    defer wg.Done()\n    for id := range jobs {\n        results&#91;id] = id * id \/\/ each job writes its own slot, so no race\n    }\n}\n\nfunc main() {\n    const numJobs, numWorkers = 6, 3\n    jobs := make(chan int, numJobs)\n    results := make(&#91;]int, numJobs)\n\n    var wg sync.WaitGroup\n    for w := 0; w &lt; numWorkers; w++ {\n        wg.Add(1)\n        go worker(jobs, results, &amp;wg)\n    }\n    for id := 0; id &lt; numJobs; id++ {\n        jobs &lt;- id\n    }\n    close(jobs)\n    wg.Wait()\n\n    fmt.Println(\"results:\", results)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>results: &#91;0 1 4 9 16 25]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">On the AWS side, these services help.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>AWS service<\/th><th>Role<\/th><\/tr><\/thead><tbody><tr><td>Application Load Balancer (ALB)<\/td><td>Spreads requests across Go instances<\/td><\/tr><tr><td>Auto Scaling, ECS or EKS<\/td><td>Adds instances or containers when traffic grows<\/td><\/tr><tr><td>RDS or Aurora<\/td><td>Managed database with read replicas and backups<\/td><\/tr><tr><td>ElastiCache (Redis)<\/td><td>Caches hot data and reduces DB load<\/td><\/tr><tr><td>S3<\/td><td>Stores files, images and logs, not on the server disk<\/td><\/tr><tr><td>SQS<\/td><td>Queues slow jobs like emails and reports for background workers<\/td><\/tr><tr><td>CloudWatch<\/td><td>Logs, metrics and alarms<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q138. What is ECS?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Amazon ECS (Elastic Container Service) is a fully managed AWS service for running Docker containers. It deploys, runs, scales and restarts your containers, so you do not manage the orchestration yourself.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without ECS, you create an EC2 instance, install Docker and start containers by hand. You also restart crashed containers and scale them manually. With ECS, you push your Go image to Amazon ECR and describe it in a <strong>task definition<\/strong>. Then an ECS <strong>service<\/strong> keeps the right number of tasks running.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ECS restarts tasks that crash or fail health checks.<\/li>\n\n\n\n<li>Tasks scale automatically based on CPU or request count.<\/li>\n\n\n\n<li>An Application Load Balancer can route traffic to the tasks.<\/li>\n\n\n\n<li>You can run them on <strong>Fargate<\/strong> (serverless, no servers to manage) or on your own EC2 instances.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">ECS is simpler than Kubernetes (EKS), so it is a common choice for Go microservices on AWS.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q139. What is a URL shortener?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A URL shortener turns a long URL into a short, unique one. For example, <code>https:\/\/www.example.com\/products\/mobile\/iphone?color=black&amp;storage=256GB<\/code> becomes <code>https:\/\/short.ly\/aB12Cd<\/code>. When someone opens the short link, the service redirects them to the original URL.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It works in two flows.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Create.<\/strong> The user sends a long URL. The service makes a unique code, saves <code>code -&gt; long URL<\/code> in a database and returns the short link.<\/li>\n\n\n\n<li><strong>Redirect.<\/strong> A user opens <code>GET \/aB12Cd<\/code>. The service looks up the code and replies with an HTTP 301 or 302 redirect.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">There are three common ways to make the code.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Base62 encoding (most common).<\/strong> Take a unique number, such as an auto-increment ID, and encode it with <code>0-9<\/code>, <code>A-Z<\/code> and <code>a-z<\/code>. Seven characters give over 3.5 trillion codes.<\/li>\n\n\n\n<li><strong>Random string.<\/strong> Generate random characters and check the database for clashes.<\/li>\n\n\n\n<li><strong>Hashing.<\/strong> Hash the URL with MD5 or SHA-256 and keep the first few characters. Then handle collisions.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This Go program encodes and decodes IDs with Base62.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n\/\/ encode turns a numeric ID into a short Base62 code.\nfunc encode(id uint64) string {\n    if id == 0 {\n        return string(alphabet&#91;0])\n    }\n    var b &#91;]byte\n    for id &gt; 0 {\n        b = append(b, alphabet&#91;id%62])\n        id \/= 62\n    }\n    \/\/ digits were built in reverse order, so flip them\n    for i, j := 0, len(b)-1; i &lt; j; i, j = i+1, j-1 {\n        b&#91;i], b&#91;j] = b&#91;j], b&#91;i]\n    }\n    return string(b)\n}\n\n\/\/ decode turns a Base62 code back into the numeric ID.\nfunc decode(code string) uint64 {\n    var id uint64\n    for _, c := range code {\n        id = id*62 + uint64(strings.IndexRune(alphabet, c))\n    }\n    return id\n}\n\nfunc main() {\n    for _, id := range &#91;]uint64{1, 61, 62, 125000, 3521614606207} {\n        code := encode(id)\n        fmt.Printf(\"id %d -&gt; %s -&gt; %d\\n\", id, code, decode(code))\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>id 1 -&gt; 1 -&gt; 1\nid 61 -&gt; z -&gt; 61\nid 62 -&gt; 10 -&gt; 62\nid 125000 -&gt; WW8 -&gt; 125000\nid 3521614606207 -&gt; zzzzzzz -&gt; 3521614606207<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">At scale, you also add a Redis cache for popular links, rate limiting, link expiry and click analytics.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q140. Why are microservices used in Golang, and what is their main purpose?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The main purpose of microservices is to break a large application into small, independent services. Each service handles one business capability, such as users, products or orders.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Independent scaling.<\/strong> Suppose the Order Service gets 5,000 requests per minute and the User Service gets 100. Then you can run ten Order instances and only one User instance, which saves money.<\/li>\n\n\n\n<li><strong>Fault isolation.<\/strong> If the Notification Service crashes, the User, Product and Order services keep working.<\/li>\n\n\n\n<li><strong>Technology choice.<\/strong> One service can use Go, while another uses Python for machine learning.<\/li>\n\n\n\n<li><strong>Faster teams.<\/strong> Team A owns the User Service and Team B owns the Order Service, so they ship in parallel.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Go is a popular choice for microservices for several reasons.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It compiles to fast native code.<\/li>\n\n\n\n<li>Goroutines handle many concurrent requests cheaply.<\/li>\n\n\n\n<li>It uses little memory and starts quickly, which suits containers.<\/li>\n\n\n\n<li>It builds a single static binary, so deployment is simple.<\/li>\n\n\n\n<li>The standard library includes HTTP, JSON and networking support.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Services talk to each other through REST APIs, gRPC, or message queues such as Kafka, RabbitMQ and Amazon SQS.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Concurrency vs Parallelism in Go<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers ask this comparison so often that it deserves a quick summary at the end of these Golang questions and answers. The table below shows the difference in one view.<\/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\/golang-questions-and-answers-diagram-2-1024x640.png\" alt=\"Golang questions and answers comparison of concurrency and parallelism\" class=\"wp-image-951\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Concurrency means dealing with many tasks at once, while parallelism means doing many tasks at the same moment on many CPU cores.<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Concurrency<\/th><th>Parallelism<\/th><\/tr><\/thead><tbody><tr><td>Meaning<\/td><td>Dealing with many tasks at once<\/td><td>Doing many tasks at the same moment<\/td><\/tr><tr><td>Needs many CPU cores<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Go tool<\/td><td>Goroutines and channels<\/td><td>Goroutines plus GOMAXPROCS above 1<\/td><\/tr><tr><td>Example<\/td><td>A web server handling many requests<\/td><td>Splitting a big calculation across cores<\/td><\/tr><tr><td>Goal<\/td><td>Good structure and responsiveness<\/td><td>Faster total work<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So Go makes concurrency easy to write, and the runtime turns it into parallelism when your machine has more than one core.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes When Answering Golang Questions<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Mixing Go with other languages:<\/strong> Go has no classes, no <code>while<\/code> loop, no inheritance and no <code>===<\/code> operator.<\/li>\n\n\n\n<li><strong>Forgetting that slices share arrays:<\/strong> always mention length, capacity and <code>append<\/code>.<\/li>\n\n\n\n<li><strong>Writing to a map from many goroutines:<\/strong> say you would protect it with a mutex.<\/li>\n\n\n\n<li><strong>Ignoring errors:<\/strong> never answer with code that drops an <code>err<\/code> without a reason.<\/li>\n\n\n\n<li><strong>Leaking goroutines:<\/strong> explain how each goroutine stops, with <code>context<\/code> or a done channel.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Your Go Interview Answers<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Start with a one-line definition,<\/strong> then give a small example.<\/li>\n\n\n\n<li><strong>Mention trade-offs,<\/strong> such as mutex vs channel or Gin vs Fiber.<\/li>\n\n\n\n<li><strong>Name the tools you use,<\/strong> such as <code>go vet<\/code>, the race detector and pprof.<\/li>\n\n\n\n<li><strong>Use real numbers<\/strong> from your projects, such as response times or memory saved.<\/li>\n\n\n\n<li><strong>Keep code idiomatic:<\/strong> check errors right away and format with gofmt.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Pick ten questions from different sections, for example Q1, Q25, Q40, Q50, Q60, Q75, Q90, Q100, Q120 and Q135. Answer each one out loud in under one minute, then compare with the answer here. Hint: record yourself, because hearing your own answer shows where you hesitate.<\/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\n<li><a href=\"https:\/\/go.dev\/doc\/effective_go\">Effective Go<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/go.dev\/doc\/faq\">Go FAQ<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/go.dev\/ref\/spec\">The Go Programming Language Specification<\/a><\/li>\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>These Golang questions and answers cover 140 questions in eight clear sections.<\/li>\n\n\n\n<li>Every full code example was run, and its output is shown.<\/li>\n\n\n\n<li>Wrong or outdated answers from the old post were corrected for Go 1.27.<\/li>\n\n\n\n<li>Concurrency questions are the largest section, because interviewers ask them most.<\/li>\n\n\n\n<li>Practise out loud and run the code, because that is how answers stick.<\/li>\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\">Go deeper one topic at a time with the 29 topic posts in our <a href=\"https:\/\/smitabharat.com\/blog\/go-interview-questions-hub\/\">Go topic-wise interview hub<\/a>. For live coding rounds, practise the <a href=\"https:\/\/smitabharat.com\/blog\/go-coding-interview-programs\/\">Go coding interview programs<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Golang questions and answers in this post cover everything interviewers ask most, from basic syntax to goroutines, REST APIs, microservices and system design. You&hellip;<\/p>\n","protected":false},"author":1,"featured_media":949,"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,135,77,126],"swapz_series":[],"class_list":["post-952","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-interview","tag-go-interview-questions","tag-golang","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>Golang Questions and Answers: 140 Tested Answers<\/title>\n<meta name=\"description\" content=\"Golang questions and answers for interviews: 140 corrected Q&amp;A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.\" \/>\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\/golang-questions-and-answers\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Golang Questions and Answers: 140 Tested Answers\" \/>\n<meta property=\"og:description\" content=\"Golang questions and answers for interviews: 140 corrected Q&amp;A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-24T03:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-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=\"83 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Golang Questions and Answers: 140 Interview Q&#038;A for 2026\",\"datePublished\":\"2026-10-24T03:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/\"},\"wordCount\":18552,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/golang-questions-and-answers-featured.png\",\"keywords\":[\"Go Interview Questions\",\"Golang\",\"Intermediate\",\"Interview Questions\"],\"articleSection\":[\"Interview\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/\",\"name\":\"Golang Questions and Answers: 140 Tested Answers\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/golang-questions-and-answers-featured.png\",\"datePublished\":\"2026-10-24T03:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:21+00:00\",\"description\":\"Golang questions and answers for interviews: 140 corrected Q&A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/golang-questions-and-answers-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/golang-questions-and-answers-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Golang Questions and Answers featured image: 140 corrected questions with tested code\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/golang-questions-and-answers\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Golang Questions and Answers: 140 Interview Q&#038;A for 2026\"}]},{\"@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":"Golang Questions and Answers: 140 Tested Answers","description":"Golang questions and answers for interviews: 140 corrected Q&A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.","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\/golang-questions-and-answers\/","og_locale":"en_US","og_type":"article","og_title":"Golang Questions and Answers: 140 Tested Answers","og_description":"Golang questions and answers for interviews: 140 corrected Q&A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.","og_url":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-24T03:30:00+00:00","article_modified_time":"2026-11-28T19:59:21+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"83 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Golang Questions and Answers: 140 Interview Q&#038;A for 2026","datePublished":"2026-10-24T03:30:00+00:00","dateModified":"2026-11-28T19:59:21+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/"},"wordCount":18552,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-featured.png","keywords":["Go Interview Questions","Golang","Intermediate","Interview Questions"],"articleSection":["Interview"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/","url":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/","name":"Golang Questions and Answers: 140 Tested Answers","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-featured.png","datePublished":"2026-10-24T03:30:00+00:00","dateModified":"2026-11-28T19:59:21+00:00","description":"Golang questions and answers for interviews: 140 corrected Q&A on basics, slices, interfaces, goroutines, channels and APIs, with tested code.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/golang-questions-and-answers-featured.png","width":2400,"height":1260,"caption":"Golang Questions and Answers featured image: 140 corrected questions with tested code"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/golang-questions-and-answers\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Golang Questions and Answers: 140 Interview Q&#038;A for 2026"}]},{"@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\/952","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=952"}],"version-history":[{"count":5,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/952\/revisions"}],"predecessor-version":[{"id":992,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/952\/revisions\/992"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/949"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=952"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=952"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=952"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=952"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}