{"id":26822627,"url":"https://github.com/aliakkas006/go-lang-basics","last_synced_at":"2026-06-17T20:32:58.833Z","repository":{"id":283800971,"uuid":"951672733","full_name":"aliakkas006/Go-lang-basics","owner":"aliakkas006","description":"Welcome to the Go In-Depth Tour 🚀 — your one-stop repository for mastering the Go programming language from the ground up to advanced concepts.","archived":false,"fork":false,"pushed_at":"2025-11-24T10:20:20.000Z","size":2809,"stargazers_count":7,"open_issues_count":5,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-11-27T22:53:17.218Z","etag":null,"topics":["arrays","closure","functions","internal-memory","pointers","receiver-functions","scope","slice","struct","variadic-function"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aliakkas006.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-20T04:03:21.000Z","updated_at":"2025-11-24T10:20:23.000Z","dependencies_parsed_at":"2025-05-16T19:28:24.130Z","dependency_job_id":"94610611-27c9-4702-892a-474c56cd0232","html_url":"https://github.com/aliakkas006/Go-lang-basics","commit_stats":null,"previous_names":["aliakkas006/go-lang-basics"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/aliakkas006/Go-lang-basics","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakkas006%2FGo-lang-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakkas006%2FGo-lang-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakkas006%2FGo-lang-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakkas006%2FGo-lang-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aliakkas006","download_url":"https://codeload.github.com/aliakkas006/Go-lang-basics/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakkas006%2FGo-lang-basics/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34465319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-17T02:00:05.408Z","response_time":127,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arrays","closure","functions","internal-memory","pointers","receiver-functions","scope","slice","struct","variadic-function"],"created_at":"2025-03-30T08:19:38.007Z","updated_at":"2026-06-17T20:32:58.826Z","avatar_url":"https://github.com/aliakkas006.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚀 Go In-depth Tour 🧭\n\nWelcome to the **Go In-Depth Tour** — your one-stop repository for mastering the **Go programming language** from the ground up to advanced concepts. Whether you're a beginner exploring Go's syntax or an experienced developer diving into **low-level memory management** and **closures**, this repo is crafted to help you learn **practically**, **visually**, and **thoroughly**.\n\nThis repository includes clear examples and explanations for the following core Go concepts:\n\n\u003cdiv id=\"top\"\u003e\u003c/div\u003e\n\n## 📚 Index\n\n- [Keywords](#keywords-in-go)\n  - [Declaration Keywords](#declaration-keywords)\n  - [Control Flow Keywords](#control-flow-keywords)\n  - [Memory \u0026 Concurrency Keywords](#memory--concurrency-keywords)\n  - [Miscellaneous Keywords](#️miscellaneous-keywords)\n  - [Complete Keyword List](#complete-keyword-list)\n  - [Go Built-in Functions](#️go-built-in-functions)\n- [Operators](#operators)\n  - [Arithmetic Operators](#arithmetic-operators)\n  - [Comparison Operators](#comparison-operators)\n  - [Logical Operators](#logical-operators)\n  - [Bitwise Operators](#bitwise-operators)\n  - [Assignment Operators](#assignment-operators)\n  - [Address \u0026 Pointer Operators](#address--pointer-operators)\n  - [Channel Operators](#channel-operators)\n- [Variables and Data Types](#variables-and-data-types)\n  - [Declaring Variables](#declaring-variables)\n  - [Data Types](#data-types)\n  - [Type Conversion](#type-conversion)\n- [Control Statements](#control-statements)\n  - [Conditional Statements](#conditional-statements)\n  - [Switch Statement](#switch-statement)\n  - [Loop Control Statements](#loop-control-statements)\n  - [Control Flow Statements](#control-flow-statements)\n  - [`defer` Statement](#defer-statement)\n- [Functions](#functions)\n  - [Function Syntax](#function-syntax)\n  - [Function with Multiple Return Values](#function-with-multiple-return-values)\n  - [Named Return Values](#named-return-values)\n  - [Recursive Functions](#recursive-functions)\n  - [Anonymous Functions](#anonymous-functions)\n  - [IIFE](#iife--immediately-invoked-function-expression)\n  - [Closures](#closures)\n  - [`defer` with Functions](#defer-with-functions)\n  - [`init` function](#️init-function)\n  - [Variadic Function](#variadic-function)\n  - [Higher Order Function (HOF)](#higher-order-function-hof)\n  - [Receiver Function](#receiver-function)\n- [Scope](#scope)\n  - [Block Scope](#block-scope)\n  - [Function Scope](#function-scope)\n  - [Package Scope](#package-scope)\n  - [File Scope](#file-scope)\n  - [Variable Shadowing](#variable-shadowing)\n  - [Lexical Scope](#lexical-scope)\n  - [Demonstrating All Scopes](#demonstrating-all-scopes)\n- [Closure](#closure)\n  - [Basic Example with Memory Management](#basic-example)\n  - [Encapsulation](#encapsulation-private-variables)\n- [Struct](#struct)\n  - [Basic Syntax](#basic-syntax-1)\n  - [Creating Struct instances](#️creating-struct-instances)\n  - [Accessing Struct Fields](#accessing-struct-fields)\n  - [Nested Structs](#nested-structs)\n  - [Anonymous Structs](#anonymous-structs)\n  - [Comparing Structs](#comparing-structs)\n- [Array](#array)\n  - [Basic Syntax](#basic-syntax-2)\n  - [Array Declaration \u0026 Initialization](#array-declaration--initialization)\n  - [Working with Arrays](#working-with-arrays)\n- [Pointer](#pointer)\n  - [Pointer Terminology](#pointer-terminology)\n  - [Pointer Syntax](#pointer-syntax)\n  - [Pointer Mechanics](#pointer-mechanics)\n- [Slice](#slice)\n  - [Slice Structure](#slice-structure)\n  - [Creating Slices](#creating-slices)\n  - [Appending to Slices](#appending-to-slices)\n  - [Summary of Slice Creation](#summary-of-slice-creation)\n- [Map](#maps)\n  - [Map Syntax](#map-syntax)\n  - [Declaring Maps](#declaring-maps)\n  - [Working with Map](#working-with-map)\n  - [Practical Example](#practical-example-word-frequency-counter)\n- [Contributions](#contributions)\n\n---\n\n# Keywords in Go\n\n\u003e In Go, keywords are reserved words that have special meaning in the language. we can't use them as variable names or identifiers. Go has just **25 keywords** that form the building blocks of the language.\n\n## Declaration Keywords\n\n| Keyword   | Purpose                           |\n| --------- | --------------------------------- |\n| `var`     | Declares variables                |\n| `const`   | Declares constants                |\n| `type`    | Declares a new type               |\n| `func`    | Declares a function               |\n| `package` | Declares the current package name |\n| `import`  | Imports packages                  |\n\n---\n\n## Control Flow Keywords\n\n| Keyword       | Purpose                                  |\n| ------------- | ---------------------------------------- |\n| `if`          | Starts a conditional block               |\n| `else`        | Specifies an alternative block           |\n| `switch`      | Multiple conditional branches            |\n| `case`        | A branch within `switch`                 |\n| `default`     | Default branch in `switch`               |\n| `for`         | Starts a loop                            |\n| `range`       | Iterates over arrays, slices, maps, etc. |\n| `goto`        | Jumps to a label                         |\n| `fallthrough` | Falls through to next case in switch     |\n| `continue`    | Skips current loop iteration             |\n| `break`       | Exits loop or switch                     |\n| `return`      | Exits from a function                    |\n| `defer`       | Delays execution until function ends     |\n\n---\n\n## Memory \u0026 Concurrency Keywords\n\n| Keyword  | Purpose                       |\n| -------- | ----------------------------- |\n| `chan`   | Declares a channel            |\n| `go`     | Starts a goroutine            |\n| `select` | Waits on multiple channel ops |\n\n---\n\n## Miscellaneous Keywords\n\n| Keyword     | Purpose                    |\n| ----------- | -------------------------- |\n| `interface` | Declares an interface type |\n| `struct`    | Declares a structure type  |\n| `map`       | Declares a map type        |\n\n---\n\n## Complete Keyword List\n\n| Keyword    | Keyword       | Keyword  | Keyword     | Keyword  |\n| ---------- | ------------- | -------- | ----------- | -------- |\n| `break`    | `default`     | `func`   | `interface` | `select` |\n| `case`     | `defer`       | `go`     | `map`       | `struct` |\n| `chan`     | `else`        | `goto`   | `package`   | `switch` |\n| `const`    | `fallthrough` | `if`     | `range`     | `type`   |\n| `continue` | `for`         | `import` | `return`    | `var`    |\n\n#### ❗ Notes:\n\n- Go also reserves some **predeclared identifiers** like `int`, `string`, `true`, `false`, `nil`, etc., which aren't keywords but are important.\n- Go has no classes, try-catch, or while—this keeps the language simple.\n- **Case-sensitive**: all keywords must be lowercase.\n\n---\n\n## Go Built-in Functions\n\n- These identifiers — `append`, `cap`, `close`, `complex`, `copy`, `delete`, `imag`, `len`, `make`, `new`, `panic`, `print`, `println`, `real`, `recover` — are **predeclared built-in functions** in Go.\n- They are **not keywords**, but they're treated specially by the compiler.\n- These functions are part of Go's **runtime** and are always available without importing any package.\n\n| Function  | Purpose                                                            |\n| --------- | ------------------------------------------------------------------ |\n| `append`  | Adds elements to the end of a slice and returns the updated slice  |\n| `cap`     | Returns the capacity of a slice, array, or channel                 |\n| `close`   | Closes a channel                                                   |\n| `complex` | Creates a complex number from two float values                     |\n| `copy`    | Copies elements from a source slice to a destination slice         |\n| `delete`  | Deletes a key-value pair from a map                                |\n| `imag`    | Returns the imaginary part of a complex number                     |\n| `len`     | Returns the length of strings, arrays, slices, maps, or channels   |\n| `make`    | Allocates and initializes slices, maps, or channels                |\n| `new`     | Allocates memory for a variable and returns a pointer to it        |\n| `panic`   | Stops the normal execution of a program (used for critical errors) |\n| `print`   | Prints values to the standard output (less commonly used)          |\n| `println` | Like `print`, but adds spaces and a newline                        |\n| `real`    | Returns the real part of a complex number                          |\n| `recover` | Regains control of a panicking goroutine (used with `defer`)       |\n\n[⬆️ Back to top](#top)\n\n---\n\n# Operators\n\n\u003e Operators are special symbols used to perform operations on variables and values. They are categorized as follows:\n\n## Arithmetic Operators\n\n| **Operator** | **Description**          | **Example** |\n| ------------ | ------------------------ | ----------- |\n| `+`          | Addition                 | `a + b`     |\n| `-`          | Subtraction              | `a - b`     |\n| `*`          | Multiplication           | `a * b`     |\n| `/`          | Division                 | `a / b`     |\n| `%`          | Modulus (Remainder)      | `a % b`     |\n| `++`         | Increment (Postfix only) | `a++`       |\n| `--`         | Decrement (Postfix only) | `a--`       |\n\n### ⚠️ Caution:\n\n- Go does **not** support prefix increment/decrement (`++a`, `--a`) — only **postfix** is allowed (`a++`, `a--`).\n\n---\n\n## Comparison Operators\n\n| **Operator** | **Description**          | **Example** |\n| ------------ | ------------------------ | ----------- |\n| `==`         | Equal to                 | `a == b`    |\n| `!=`         | Not equal to             | `a != b`    |\n| `\u003e`          | Greater than             | `a \u003e b`     |\n| `\u003c`          | Less than                | `a \u003c b`     |\n| `\u003e=`         | Greater than or equal to | `a \u003e= b`    |\n| `\u003c=`         | Less than or equal to    | `a \u003c= b`    |\n\n### Note:\n\n- These operators return `true` or `false` and are commonly used in conditional statements.\n\n---\n\n## Logical Operators\n\n| **Operator** | **Description** | **Example** |\n| ------------ | --------------- | ----------- |\n| `\u0026\u0026`         | Logical AND     | `a \u0026\u0026 b`    |\n| `\\|\\|`       | Logical OR      | `a \\|\\| b`  |\n| `!`          | Logical NOT     | `!a`        |\n\n### Notes:\n\n- `\u0026\u0026` returns `true` if **both** operands are `true`.\n- `||` returns `true` if **at least one** operand is `true`.\n- `!` inverts the boolean value (i.e., `!true` is `false`).\n- Logical expressions are **short-circuited**:\n  - `a \u0026\u0026 b` stops evaluating if `a` is `false`\n  - `a || b` stops evaluating if `a` is `true`\n\n---\n\n## Bitwise Operators\n\n| **Operator**        | **Description**     | **Example**             |\n| ------------------- | ------------------- | ----------------------- |\n| `\u0026`                 | Bitwise AND         | `a \u0026 b`                 |\n| \u003ccode\u003e\u0026#124;\u003c/code\u003e | Bitwise OR          | \u003ccode\u003ea \u0026#124; b\u003c/code\u003e |\n| `^`                 | Bitwise XOR         | `a ^ b`                 |\n| `\u0026^`                | Bit clear (AND NOT) | `a \u0026^ b`                |\n| `\u003c\u003c`                | Left shift          | `a \u003c\u003c b`                |\n| `\u003e\u003e`                | Right shift         | `a \u003e\u003e b`                |\n\n---\n\n## Assignment Operators\n\n| **Operator**         | **Description**        | **Example**              |\n| -------------------- | ---------------------- | ------------------------ |\n| `=`                  | Simple assignment      | `a = b`                  |\n| `+=`                 | Add and assign         | `a += b`                 |\n| `-=`                 | Subtract and assign    | `a -= b`                 |\n| `*=`                 | Multiply and assign    | `a *= b`                 |\n| `/=`                 | Divide and assign      | `a /= b`                 |\n| `%=`                 | Modulus and assign     | `a %= b`                 |\n| `\u0026=`                 | Bitwise AND and assign | `a \u0026= b`                 |\n| \u003ccode\u003e\u0026#124;=\u003c/code\u003e | Bitwise OR and assign  | \u003ccode\u003ea \u0026#124;= b\u003c/code\u003e |\n| `^=`                 | Bitwise XOR and assign | `a ^= b`                 |\n| `\u003c\u003c=`                | Left shift and assign  | `a \u003c\u003c= b`                |\n| `\u003e\u003e=`                | Right shift and assign | `a \u003e\u003e= b`                |\n\n---\n\n## Address \u0026 Pointer Operators\n\n| **Operator** | **Description**     | **Example** |\n| ------------ | ------------------- | ----------- |\n| `\u0026`          | Address of          | `\u0026a`        |\n| `*`          | Pointer dereference | `*ptr`      |\n\n### Notes:\n\n- `\u0026a` returns the memory address of variable `a`.\n- `*ptr` accesses the value stored at the memory address held by `ptr`.\n\n---\n\n## Channel Operators\n\n| **Operator** | **Description**             | **Example**           |\n| ------------ | --------------------------- | --------------------- |\n| `\u003c-`         | Send/Receive from a channel | `ch \u003c- x`, `x = \u003c-ch` |\n\n### Notes:\n\n- `ch \u003c- x` sends the value `x` into the channel `ch`.\n- `x = \u003c-ch` receives a value from the channel `ch` and stores it in `x`.\n\n[⬆️ Back to top](#top)\n\n---\n\n# Variables and Data Types\n\nGo is a statically typed, compiled language with a rich set of built-in data types and flexible variable declaration syntax.\n\n## Declaring Variables\n\n- ### Explicit Declaration with `var` keyword\n\n```go\nvar name string       // Declaration without initialization (default: \"\")\nvar age int = 24      // Declaration with initialization\nvar height = 165.5    // Type inference (float64)\n```\n\n- ### Short Declaration\n\n```go\nname := \"Ali Akkas\"       // string\nage := 24             // int\nheight := 165.5        // float64\nactive := true        // bool\n```\n\n- ### Multiple Variable Declaration 🧩\n\n```go\nvar (\n\tname = \"ali\"\n\tage  = 24\n)\n\nx, y := 10, 20\n```\n\n### Zero Values\n\n| Type      | Zero Value   |\n| --------- | ------------ |\n| int       | `0`          |\n| float64   | `0.0`        |\n| string    | `\"\"` (empty) |\n| bool      | `false`      |\n| pointer   | `nil`        |\n| slice/map | `nil`        |\n\n---\n\n## Data Types\n\n\u003e Go is statically typed — each variable must have a defined type (either explicitly or inferred).\n\n### Basic Types\n\n| Type                                            | Description     | Example                     |\n| ----------------------------------------------- | --------------- | --------------------------- |\n| `int`, `int8`, `int16`, `int32` `int64`, `uint` | Integer types   | `var age int = 30`          |\n| `float32`, `float64`                            | Floating points | `var price float64 = 9.99`  |\n| `string`                                        | Text (UTF-8)    | `var name string = \"Go\"`    |\n| `bool`                                          | Boolean values  | `var valid bool = true`     |\n| `complex64`, `complex128`                       | Complex numbers | `var c complex128 = 1 + 2i` |\n\n### Composite Types\n\n| Type        | Description                        | Example                                       |\n| ----------- | ---------------------------------- | --------------------------------------------- |\n| `array`     | Fixed-size sequence of elements    | `arr := [3]int{1, 2, 3}`                      |\n| `slice`     | Dynamic-length version of array    | `s := []int{1, 2, 3}`                         |\n| `map`       | Key-value store                    | `m := map[string]int{\"a\": 1}`                 |\n| `struct`    | Collection of fields (custom type) | `type Person struct { Name string; Age int }` |\n| `pointer`   | Holds memory address of a value    | `var p *int`                                  |\n| `interface` | Defines behavior (methods)         | `type Shape interface { Area() float64 }`     |\n| `channel`   | Communication between goroutines   | `ch := make(chan int)`                        |\n| `function`  | First-class functions              | `func add(a, b int) int { return a + b }`     |\n\n### Constants\n\n- Use `const` to declare immutable values\n\n```go\nconst Pi = 3.1415\nconst Lang = \"Go\"\n```\n\n## Type Conversion\n\n- Go is **strictly typed** — implicit conversion is not allowed.\n- Use explicit conversion with the type name.\n\n```go\nvar i int = 42\nvar f float64 = float64(i)\nvar u uint = uint(f)\n\n// String to bytes and back\nstr := \"hello\"\nbytes := []byte(str)\nnewStr := string(bytes)\n```\n\n[⬆️ Back to top](#top)\n\n---\n\n# Control Statements\n\n\u003e Control statements are fundamental building blocks that determine the flow of program execution.\n\u003e Control statements in Go allow us to manage the flow of execution within loops and functions.\n\u003e They provide ways to **skip iterations**, **exit loops early**, **jump to labeled code**, and **return from functions**.\n\n## Conditional Statements\n\n- ### `if` Statement\n\n```go\nif temp \u003e 5 {\n\n\tfmt.Println(\"Condition Satisfied!\")\n}\n```\n\n- ### `if-else` Statement\n\n```go\nif marks \u003e 40 {\n\tfmt.Println(\"Passed!\")\n} else {\n\tfmt.Println(\"Failed!\")\n}\n```\n\n- ### `if else-if` Ladder\n\n```go\nif marks \u003e= 80 {\n\tgrade = \"A+\"\n} else if marks \u003e= 70 {\n\tgrade = \"A\"\n} else if marks \u003e= 60 {\n\tgrade = \"B\"\n} else if marks \u003e= 40 {\n\tgrade = \"C\"\n} else {\n\tgrade = \"F\"\n}\n```\n\n- ### Short Statement\n\nGo allows a short statement to execute before the condition.\n\n```go\nif err := process(); err != nil {\n\tfmt.Println(err)\n}\n```\n\n## Switch Statement\n\n- ### Basic Switch\n\n```go\nday := \"Friday\"\nswitch day {\ncase \"Monday\":\n\tfmt.Println(\"Start of the week\")\ncase \"Friday\":\n\tfmt.Println(\"Weekend coming\")\ndefault:\n\tfmt.Println(\"Weekend!\")\n}\n```\n\n- ### Switch with `no expression`\n\n```go\ntemperature := 30\nswitch {\ncase temperature \u003e 30:\n\tfmt.Println(\"Hot weather\")\ncase temperature \u003e= 25:\n\tfmt.Println(\"Room temperature\")\ndefault:\n\tfmt.Println(\"Cold weather\")\n\t}\n```\n\n- ### `Fallthrough` within switch\n\n\u003e In Go, the fallthrough keyword is used within a switch statement to force execution to continue to the next case, even if the next case expression does not match.\n\n```go\nswitch num := 1; num {\ncase 1:\n\tfmt.Println(\"Case 1\")\n\tfallthrough\ncase 2:\n\tfmt.Println(\"Case 2\")\n\tfallthrough\ncase 3:\n\tfmt.Println(\"Case 3\")\n}\n```\n\n```bash\nOutput:\nCase 1\nCase 2\nCase 3\n```\n\n\u003e ⚠️ fallthrough ignores the next case's condition and just executes its body.\n\n## Loop Control Statements\n\n- ### Traditional For Loop\n\nSyntax:\n\n```go\nfor init; condition; inc/dec {\n    ---\n}\n```\n\nExample:\n\n```go\nfor i := 0; i \u003c 5; i++ {\n\tfmt.Println(i)\n}\n```\n\n- ### While-style Loop\n\nSyntax:\n\n```go\nfor condition {\n\t---\n}\n```\n\nExample:\n\n```go\ncount := 5\nfor count \u003c 5 {\n\tcount++\n}\n```\n\n- ### Infinite Loop\n\nSyntax:\n\n```go\nfor {\n\t---\n\tbreak\t// needed to exit\n}\n```\n\nExample:\n\n```go\nfor {\n    data := readData()\n    if data == nil {\n        break\n    }\n    process(data)\n}\n```\n\n- ### Range-based Loop\n\nSyntax:\n\n```go\nfor index, value := range arr {\n    ---\n}\n```\n\nExample:\n\n```go\n// Loop on array/slice\narr := []int{1, 2, 3, 4, 5}\n\nfor i, val := range arr {\n\tfmt.Printf(\"%d: %d\\n\", i, val)\n}\n```\n\n```go\n// Loop on map\nm := map[string]int{\"x\": 10, \"y\": 20, \"z\": 30}\n\nfor key, val := range m {\n\tfmt.Printf(\"%s: %d\\n\", key, val)\n}\n```\n\n```go\n// Loop on string\nstr := \"Akkas\"\n\nfor i, val := range str {\n\tfmt.Printf(\"%d: %s\\n\", i, string(val))\n}\n```\n\n```go\n// Channel\nfor item := range channel {\n    process(item)\n}\n```\n\n## Control Flow Statements\n\n- ### `break`\n\n```go\nfor i := 0; ; i++ {\n    if i == 5 {\n        break\n    }\n    fmt.Println(i)\n}\n```\n\n- ### `continue`\n\n```go\nfor i := 0; i \u003c 10; i++ {\n    if i%2 == 0 {\n        continue\n    }\n    fmt.Println(i)\n}\n```\n\n- ### Labels with break and continue\n\n```go\nouter:\nfor i := 1; i \u003c= 3; i++ {\n\tfor j := 1; j \u003c= 3; j++ {\n\t\tif i*j \u003e 4 {\n\t\t\tbreak outer\n\t\t}\n\t\tfmt.Println(\"i:\", i, \"j:\", j)\n\t}\n}\n```\n\n- ### `goto`: Jump to Labeled Code\n\n```go\nfunc main() {\n\tcount := 0\nstart:\n\tif count \u003c 3 {\n\t\tfmt.Println(\"Count:\", count)\n\t\tcount++\n\t\tgoto start\n\t}\n}\n```\n\n- ### return: Exit from Function\n\n```go\nfunc greet(name string) {\n\tif name == \"\" {\n\t\treturn\n\t}\n}\n```\n\n### Summary Table\n\n| Statement  | Description                                     |\n| ---------- | ----------------------------------------------- |\n| `break`    | Exits current loop or switch                    |\n| `continue` | Skips current iteration of loop                 |\n| `goto`     | Jumps to a labeled line of code                 |\n| `return`   | Exits the current function                      |\n| Label      | Named target for `goto`, `break`, or `continue` |\n\n## ⚡ `defer` Statement\n\n```go\nfunc readFile() {\n    f, err := os.Open(\"file.txt\")\n\n    if err != nil {\n        return\n    }\n\n    defer f.Close() // Executes when function exits\n\n    // Process file\n}\n```\n\n- Defers execute in LIFO order\n- Arguments are evaluated immediately\n- Useful for resource cleanup\n\n[⬆️ Back to top](#top)\n\n---\n\n# Functions\n\n- A function is a reusable block of code that performs a specific task.\n- A parameter is a variable named in the function definition.\n- An argument is the actual value that is passed to the function when it is called.\n\n## Function Syntax\n\n```go\nfunc functionName(param1 type1, param2 type2) returnType {\n\t// --- function body\n\treturn value\n}\n```\n\nExample:\n\n```go\nfunc add(a int, b int) int {\n\treturn a + b\n}\n```\n\n## Function with Multiple Return Values\n\n```go\nfunc divide(a, b int) (int, int) {\n\tquotient := a / b\n\tremainder := a % b\n\treturn quotient, remainder\n}\n```\n\n## Named Return Values\n\n```go\nfunc getStats(nums []int) (sum int, count int) {\n\tfor _, n := range nums {\n\t\tsum += n\n\t}\n\tcount = len(nums)\n\n\treturn \t\t// Automatically returns named values - (sum, count)\n}\n```\n\n## Recursive Functions\n\n- A function that calls itself.\n\n```go\nfunc factorial(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn n * factorial(n-1)\n}\n```\n\n## Anonymous Functions\n\n- An anonymous function is a function that doesn’t have a name.\n- It is useful when you want to create an inline function.\n- We Can assign an anonymous function to a variable.\n\n```go\nadd := func(x, y int) int {\n\treturn x + y\n}\n\nadd(2, 3) \t// 5\n```\n\n## IIFE : Immediately Invoked Function Expression\n\n```go\nfunc(x, y int) {\n\tsum := x + y\n\tfmt.Println(sum)\n}()\n```\n\n## Closures\n\n- Closure allows functions to **remember** and **access variables** from their surrounding **lexical scope**, even after the outer function has finished executing.\n\n```go\nfunc counter() func() int {\n\ti := 0\n\n\top := func() int {\n\t\ti++\n\t\treturn i\n\t}\n\n\treturn op\n}\n\nnext := counter()\n\nnext()\t// 1\nnext()  // 2\n```\n\n## `defer` with Functions\n\n- Use `defer` to delay execution until the surrounding function returns.\n\n```go\nfunc process() {\n\tdefer fmt.Println(\"Finished!\")\n\n\tfmt.Println(\"Processing...\")\n}\n```\n\nOutput:\n\n```bash\nProcessing...\nFinished!\n```\n\n## `init` function\n\n- We can't call this function, Computer calls this function autometically.\n- It will called at the beginning of the program execution (even before main function's called).\n\nExample:\n\n```go\npackage main\nimport \"fmt\"\n\nfunc init() {\n\tfmt.Println(\"init function executed\")\n}\n\nfunc main() {\n\tfmt.Println(\"main function executed\")\n}\n```\n\nOutput:\n\n```bash\ninit function executed\nmain function executed\n```\n\n### Key Characteristics of `init()`\n\n| Property             | Description                                        |\n| -------------------- | -------------------------------------------------- |\n| Signature            | `func init()` — no parameters, no return value     |\n| Automatic Invocation | Called before `main()` and after global variables  |\n| Multiple `init`s     | A package can have **multiple** `init()` functions |\n| File Order           | Run in the order files are compiled                |\n| Package Order        | Dependencies' `init()` run **before** yours        |\n\n---\n\n## Variadic Function\n\n- A variadic function is a function that accepts a **variable number of arguments** of the same data type.\n- use the ... (ellipsis) syntax before the type to define it.\n\nBasic Syntax:\n\n```go\nfunc funcName(params ...type) {\n\t// --- function body\n\treturn\n}\n```\n\nExample:\n\n```go\nfunc variadicFunc(numbers ...int) { // numbers := []int{1, 2, 3, 4, 5}\n\tfmt.Println(numbers, len(numbers), cap(numbers)) // [1, 2, 3, 4, 5], len = 5, cap = 5\n}\n```\n\n```go\nfunc sum(nums ...int) int { // nums := []int{1, 2, 3}\n\ttotal := 0\n\tfor _, num := range nums {\n\t\ttotal += num\n\t}\n\treturn total\n}\n```\n\n```go\nfunc main() {\n\tvariadicFunc(1, 2, 3, 4, 5)\n\n\tsummation := sum(1, 2, 3)      // 6\n\tsummation2 := sum(1, 2, 3, 4, 5) // 15\n}\n```\n\n### Summary of Variadic Function\n\n- When we call a variadic function, Go converts the **arguments into a slice**.\n- The variadic parameter is **implemented as a slice under the hood**.\n- The compiler generates code to automatically create this slice.\n- Calling with no variadic args creates a nil slice: **numbers := []int**\n\n---\n\n## Higher Order Function (HOF)\n\n- A function that takes another **function as a parameter** or **returns a function** as a result or does **both** is called a higher-order function.\n\n```go\nadd := func(a, b int) {\n\tsum := a + b\n\tprintln(sum)\n}\n```\n\n```go\nfunc processOperation(a, b int, cb func(x, y int)) func(x, y int) {\n\t// Execute op func\n\tcb(a, b)\n\n\treturn func div(x, y int) {\n\tres := x / y\n\tfmt.Println(res)\n\t}\n}\n```\n\n```go\nfunc main() {\n\tresult := processOperation(10, 20, add)\t\t// Executes: add(10, 20) → prints 30\n\tresult(20, 10)\t// Executes: div(20, 10) → prints 2\n}\n```\n\n### Why Use Higher-Order Functions?\n\n| Benefit         | Description                                        |\n| --------------- | -------------------------------------------------- |\n| Reusability     | Abstract repeated patterns like filtering, mapping |\n| Customizability | Inject behavior as parameters                      |\n| Cleaner Code    | Reduce boilerplate with functional patterns        |\n| Composition     | Build complex logic from small reusable functions  |\n\n---\n\n## Receiver Function\n\n- A receiver function is a function that binds to a type (usually a `struct`) and can be called like a method.\n- `ReceiverType` is usually a `struct`.\n- The receiver can be `value` or `pointer`.\n\n### Basic Syntax\n\n```go\nfunc (receiver ReceiverType) MethodName(args) ReturnType {\n    // --- Function body\n}\n```\n\n### Example\n\n```go\npackage main\nimport \"fmt\"\n\ntype User struct {\n\tName  string // Property\n\tAge   int\n\tEmail string\n}\n\n// Receiver Function (receive only User type's variable)\nfunc (user User) printDetails() {\n\tfmt.Println(\"Name: \", user.Name)\n\tfmt.Println(\"Age: \", user.Age)\n\tfmt.Println(\"Email: \", user.Email)\n}\n\nfunc (user User) call(x int) {\n\tfmt.Println(\"Name: \", user.Name)\n\tfmt.Println(\"Age: \", user.Age)\n\n\tfmt.Println(\"X: \", x)\n}\n\nfunc main() {\n\tuser := User{\n\t\tName:  \"Ali\",\n\t\tAge:   24,\n\t\tEmail: \"ali@gmail.com\",\n\t}\n\n\tuser.printDetails()\n\n\tuser_2 := User{\n\t\tName: \"Ali Akkas\",\n\t\tAge:  24,\n\t}\n\n\tuser_2.call(30)\n}\n```\n\n### 1. Compilation Phase (Compile Time)\n\n#### Code segment (`Read-only`, contains `function definitions` and `types` )\n\n| 📍 Address | 📜 Content                                                                                                                                                            |\n| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `0x0000`   | `type User struct {`\u003cbr\u003e    `Name string`\u003cbr\u003e    `Age int`\u003cbr\u003e    `Email string`\u003cbr\u003e`}`                                                                               |\n| `0x0100`   | `func (user User) printDetails() {`\u003cbr\u003e    `fmt.Println(\"Name:\", user.Name)`\u003cbr\u003e    `fmt.Println(\"Age:\", user.Age)`\u003cbr\u003e    `fmt.Println(\"Email:\", user.Email)`\u003cbr\u003e`}` |\n| `0x0200`   | `func (user User) call(x int) {`\u003cbr\u003e    `fmt.Println(\"Name:\", user.Name)`\u003cbr\u003e    `fmt.Println(\"Age:\", user.Age)`\u003cbr\u003e    `fmt.Println(\"X:\", x)`\u003cbr\u003e`}`                 |\n| `0x0300`   | `func main() { ... }`                                                                                                                                                 |\n\n### 2. Execution Phase (Run Time)\n\n#### **Stack Frame** (grows downward, contains local variables and args)\n\n| 📍 Address | 📦 Content                                                                                                 |\n| ---------- | ---------------------------------------------------------------------------------------------------------- |\n| `0xFF00`   | `user (User struct)`\u003cbr\u003e• Name: `\"Ali\"` (`0xA100`)\u003cbr\u003e• Age: `24`\u003cbr\u003e• Email: `\"ali@gmail.com\"` (`0xA200`) |\n| `0xFE00`   | `user_2 (User struct)`\u003cbr\u003e• Name: `\"Ali Akkas\"` (`0xA300`)\u003cbr\u003e• Age: `24`\u003cbr\u003e• Email: `\"\"` (nil)           |\n\n#### Heap Memory (Dynamic Allocation)\n\n- 🔗 Strings in Go are reference types, stored dynamically on the heap and referenced via pointers.\n\n| 📍 Address | 🧵 Content        |\n| ---------- | ----------------- |\n| `0xA100`   | `\"Ali\"`           |\n| `0xA200`   | `\"ali@gmail.com\"` |\n| `0xA300`   | `\"Ali Akkas\"`     |\n\n#### Function Call Operations\n\n| 🧪 Operation          | 🔍 Details                                                                                                                       |\n| --------------------- | -------------------------------------------------------------------------------------------------------------------------------- |\n| `user.printDetails()` | • Copies `user` struct from `0xFF00` into a new stack frame.\u003cbr\u003e• Accesses `Name` and `Email` via heap at `0xA100` and `0xA200`. |\n| `user_2.call(30)`     | • Copies `user_2` from `0xFE00` to the call frame.\u003cbr\u003e• Argument `x=30` pushed to stack.\u003cbr\u003e• Name resolved from `0xA300`.       |\n\n### Pointer Receiver\n\n- func (t \\*Type)\n- Works on the original struct (modifiable).\n\n```go\nfunc (usr *User) Birthday() {\n    usr.Age++ // Modifies the original User data\n}\n\nuser := User{\"Akkas\", 24}\nperson.Birthday()\nfmt.Println(person.Age) // 25 (changed)\n```\n\nReceiver functions are Go’s way of attaching behavior to data without full-blown OOP. They enable:\n\n\u003e Clean, object-like APIs\n\u003e Polymorphism via interfaces\n\u003e Explicit control over mutability\n\n### 🚫 Receiver Functions Only for Types\n\nWe cannot attach a method to a built-in type like `int`. Only **custom types (structs, named types)** can have methods.\n\n[⬆️ Back to top](#top)\n\n---\n\n# Scope\n\nScope defines the **region of code** where a **variable**, **function**, or **other identifier** can be **accessed**.\n\n\u003e It determines the visibility and lifetime of program elements, preventing naming conflicts and managing memory efficiently.\n\nThere are **four primary scopes** in Go:\n\n1. **Block Scope**\n2. **Function Scope**\n3. **Package Scope**\n4. **File Scope**\n\n## Block Scope\n\n- Variables declared inside **`{}`** blocks are only visible within that block\n- Includes control structures (**`if`**, **`for`**, **`switch`**), **`functions`**, and **`explicit blocks`**\n\n```go\nfunc main() {\n    x := 10 \t// Outer scope variable\n\n    {\n        y := 30 \t// Inner scope variable\n        fmt.Println(x, y) \t// Valid (10 30)\n    }\n\n    fmt.Println(y) \t// Compile error: undefined:y\n}\n```\n\n---\n\n## Function Scope\n\n- Variables declared inside functions are visible only within that function.\n- Includes parameters and return values.\n\n```go\nfunc calculate(a, b int) (result int) {\t\t// a, b, and result are function-scoped\n    temp := a * b \t// Also function-scoped\n    return temp + 10\n}\n\nfunc main() {\n\tresult := calculate(10, 20)\n\tfmt.Println(result) // 210\n    fmt.Println(temp) // Error: undefined:temp\n}\n```\n\n\u003e ⚠️ These variables are re-created every time the function is called.\n\n---\n\n## Package Scope\n\n- Variables declared **outside of functions** are accessible **anywhere in the same package**.\n- Can be exported (visible to other packages) if capitalized.\n\n```go\npackage main\n\nvar msg = \"Package-scoped variable\" // Not exported\nvar Msg = \"Package-scoped variable\" // Exported\n\nfunc show() {\t// Not Exported\n    fmt.Println(msg) // Works\n}\n\nfunc Add(x, y int) int {\t// Exported\n\treturn x + y\n}\n\nfunc main() {\n    fmt.Println(msg) // Works\n}\n```\n\n\u003e ✅ Package-scoped variables **persist for the lifetime** of the program.\n\u003e ⚠️ Can lead to **race conditions** in concurrent code.\n\n---\n\n## File Scope\n\n- Imported packages are file-scoped.\n\n```go\npackage main\n\nimport (\n    \"fmt\"  // Only visible in this file\n    m \"math\"  // File-scoped alias\n)\n\nvar _ = secretHelper() // File-scoped initialization\n\nfunc main() {\n    fmt.Println(m.Sqrt(4))\n}\n```\n\n---\n\n## Variable Shadowing\n\n- When an **inner scope variable** declares **same name** as **outer scope variable**.\n\n```go\nx := \"Outer-scope variable\"\n{\n    x := \"Inner-scope variable\" \t// Shadows outer scope variable x\n    fmt.Println(x) \t// Inner-scope variable\n}\nfmt.Println(x) \t// Outer-scope variable\n```\n\n\u003e ⚠️ Shadowing can cause bugs — avoid reusing variable names in nested scopes unless intentional.\n\n---\n\n## Lexical Scope\n\n\u003e Lexical scope (also called static scope) is a fundamental concept in Go that determines how and where variables, functions, and other identifiers are accessible based on their physical location in the source code. Unlike dynamic scope (which determines visibility at runtime), lexical scope is determined at compile time.\n\n```go\nfunc outerFunc() func() int {\n    count := 0 \t\t// Lexically-scoped to outerFunc\n\n    return func() int {\n        count++ \t\t// The inner function \"closes over\" count\n        return count\n    }\n}\n\nfunc main() {\n    counter := outerFunc()\n    fmt.Println(counter()) \t\t// 1\n    fmt.Println(counter()) \t\t// 2 (count persists)\n}\n```\n\n- The inner function maintains a reference to count (not a copy).\n- This is possible because Go uses **lexical scoping**.\n\n### Lexical vs Dynamic Scope Comparison\n\n| Feature        | Lexical Scope (Go)      | Dynamic Scope (e.g., Bash) |\n| -------------- | ----------------------- | -------------------------- |\n| Resolution     | At compile time         | At runtime                 |\n| Access Rules   | Based on code structure | Based on call stack        |\n| Performance    | Faster (resolved early) | Slower (runtime lookup)    |\n| Predictability | More predictable        | Less predictable           |\n\n---\n\n## Demonstrating All Scopes\n\n```go\npackage main\n\nimport (\n    \"fmt\"  // Only visible in this file\n    m \"math\"  // File-scoped alias\n)\n\nvar global = \"package-scope\" \t// package scope\n\nfunc main() {\n\tlocal := \"function-scope\"\n\n\tif true {\n\t\tblock := \"block-scope\"\n\n\t\tfmt.Println(global)\t\t// Can access global variable\n\t\tfmt.Println(local)\t\t// Can access local variable\n\t\tfmt.Println(block)\t\t// Can access block variable\n\t}\n\n\tfmt.Println(block)  // Not accessible here\n\n\tval := m.Sqrt(4) \t// File-scope\n\tfmt.Println(val)\n}\n```\n\n[⬆️ Back to top](#top)\n\n---\n\n# Closure\n\nClosures are a powerful concept in Go that allow functions to **remember** and **access variables** from their surrounding lexical scope, even after the outer function has finished executing. They are often used for:\n\n- **Encapsulation** (data privacy)\n- **Function factories** (dynamically generating functions)\n- **Callbacks** (event handlers, async operations)\n- **Stateful functions** (maintaining state between calls)\n\n## Basic Example:\n\nClosures in Go are **anonymous functions** that capture variables from their surrounding scope. They are useful when we want a function with persistent state.\n\n```go\npackage main\nimport \"fmt\"\n\nconst a = 10\nvar p = 100\n\nfunc outer() func() {\n\tmoney := 500\n\tage := 24\n\n\tshow := func() {\n\t\tmoney = money + a + p\n\t\tfmt.Println(\"Money: \", money)\n\t}\n\n\treturn show\n}\n\nfunc call() {\n\tincr_1 := outer()\n\tincr_1()    // 610\n\tincr_1()    // 720\n\n\tfmt.Println(\"---- Second incremetnt ------\")\n\n\tincr_2 := outer()\n\tincr_2()    // 610\n\tincr_2()    // 720\n}\n\nfunc main(){\n\tcall()\n}\n\nfunc init(){\n\tfmt.Println(\"==== Bank ====\")\n}\n```\n\n### 1. Compilation Phase (Compile Time) 🛠️\n\n#### Code segment (`Read-only`, contains `function definitions` and `types` )\n\n| 📜 Address | 📜 Content                                      |\n| ---------- | ----------------------------------------------- |\n| `0x0000`   | `const a = 10`                                  |\n| `0x0100`   | `func outer()` with local variables and closure |\n|            | - `money := 500`                                |\n|            | - `age := 24`                                   |\n|            | - `show := func() { ... }`                      |\n|            | - `return show`                                 |\n| `0x0200`   | Anonymous closure inside `outer()`              |\n|            | - `money = money + a + p`                       |\n|            | - `fmt.Println(\"Money:\", money)`                |\n| `0x0300`   | `func call() { ... }`                           |\n| `0x0400`   | `func main() { call() }`                        |\n| `0x0500`   | `func init()`                                   |\n|            | - `fmt.Println(\"==== Bank ====\")`               |\n\n- Variables captured by a closure are lifted to the **heap** by the escape analysis of the go compiler.\n- **Escape analysis** is a process performed by the Go compiler to determine whether a variable can be allocated on the stack or must be allocated on the heap\n\n### 2. Execution Phase (Run Time)\n\n- The `init()` function runs **before** `main()`\n- Prints: ==== Bank ====\n\n\u003c!-- ####  **Stack Frame** (grows downward, contains local variables and args) --\u003e\n\n- Global variable `p` is initialized in the **Data Segment**.\n\n#### Data Segment\n\n| Address  | Content   |\n| -------- | --------- |\n| `0xD000` | `p = 100` |\n\n#### First `call()` Execution\n\n#### ➤ First `outer()` Call (creates `incr_1`)\n\n- A new **stack frame** is created.\n- Local variables are placed on the **stack**.\n\n#### Stack (outer call 1)\n\n| Address  | Content                                       |\n| -------- | --------------------------------------------- |\n| `0xF100` | `money = 500`                                 |\n| `0xF108` | `age = 24`                                    |\n| `0xF110` | `show (closure)` → points to code at `0x0200` |\n\n#### Heap Allocation (Closure Capture)\n\nClosure captures `money` and **escapes** the stack, hence moved to the **heap**.\n\n| Address  | Content                                        |\n| -------- | ---------------------------------------------- |\n| `0xH100` | Closure environment (refers to `money@0xF100`) |\n\n#### First `incr_1()` Execution\n\n- Reads `money` from closure (heap): `500`\n- Reads `a` (constant) from code segment: `10`\n- Reads `p` (global var) from data segment: `100`\n\n**New Value**: `500 + 10 + 100 = 610`\n\nHeap after update: 0xH100.money = 610\n\n#### Second `incr_1()` Execution\n\n**New Value**: `610 + 10 + 100 = 720`\n\nHeap: 0xH100.money = 720\n\n---\n\n## Encapsulation (private variables)\n\n```go\nfunc newBankAccount(initialBalance float64) (func(float64), func() float64) {\n    balance := initialBalance \t// \"private\" variable\n\n    deposit := func(amount float64) {\n        balance += amount\n    }\n\n    getBalance := func() float64 {\n        return balance\n    }\n\n    return deposit, getBalance\n}\n\nfunc main() {\n    deposit, getBalance := newBankAccount(100.0)\n    deposit(50.0)\n    fmt.Println(getBalance()) // 150.0\n}\n```\n\n- `balance` moves from stack to heap because it's referenced after `newBankAccount` returns.\n- Both closures share the same `balance` reference.\n- The `balance` variable is effectively private, only accessible through the returned functions.\n- `balance` is hidden from outside access.\n\n[⬆️ Back to top](#top)\n\n---\n\n# Struct\n\n\u003e Structs are one of the most important features in Go for organizing and managing data.\n\u003e A struct is a **composite data type** that groups together fields (variables) under a single name.\n\n## Basic Syntax\n\n```go\ntype StructName struct {\n\tField1 datatype1\n\tField2 datatype2\n\tField3 datatype3\n}\n```\n\n```go\ntype Person struct {\n    Name string\n    Age  int\n    City string\n}\n```\n\n## Creating Struct instances\n\n### Field Initialization\n\n```go\np1 := Person{\n    Name: \"Akkas\",\n    Age:  24,\n    City: \"Dhaka\",\n}\n```\n\n### Positional Initialization (Order matters!)\n\n```go\np2 := Person{\"Anis\", 25, \"Chittigong\"}  // Must follow struct field order\n```\n\n### Zero-value Initialization\n\n```go\nvar p3 Person \t// All fields get their zero values\nfmt.Println(p3) // Output: { 0 }\n```\n\n### Using **new()** (Returns a Pointer)\n\n```go\np4 := new(Person) // p4 is a *Person (pointer)\np4.Name = \"Ali\"\n```\n\n---\n\n## Accessing Struct Fields\n\nUse the **.** (dot) operator to access fields.\n\n```go\nfmt.Println(p1.Name) // \"Akkas\"\np1.Age = 30          // Modify a field\n```\n\n## Nested Structs\n\nExample: Address inside Person\n\n```go\ntype Address struct {\n    Street  string\n    Country string\n}\n\ntype Person struct {\n    Name    string\n    Age     int\n    Address Address // Nested struct\n}\n\n// Initialization\np := Person{\n    Name: \"Ali Akkas\",\n    Age:  24,\n    Address: Address{\n        Street:  \"123 Jatrabari\",\n        Country: \"Bangladesh\",\n    },\n}\n\n// Accessing nested fields\nfmt.Println(p.Address.Country) // \"Bangladesh\"\n```\n\n## Anonymous Structs\n\n- One-time use.\n- If we need a struct for a short-lived purpose, we can define it inline.\n\n```go\ntemp := struct {\n    ID    int\n    Value string\n}{\n    ID:    1,\n    Value: \"test_value\",\n}\n\nfmt.Println(temp.Value)  // \"test_value\"\n```\n\n## Comparing Structs\n\n- Structs can be compared **only if all fields are comparable**.\n\n```go\np1 := Person{\"Akkas\", 24, \"Bangladesh\"}\np2 := Person{\"Akkas\", 24, \"Bangladesh\"}\n\nfmt.Println(p1 == p2) // true\n```\n\n### 💡Final Thoughts\n\nStructs are the backbone of data organization in Go. They provide:\n\n- **Type safety**\n- **Flexibility** (composition over inheritance)\n- **Clean code** (group related data)\n\n[⬆️ Back to top](#top)\n\n---\n\n# Array\n\n\u003e Arrays in Go are fixed-size, homogeneous (same type) data structures that store elements in contiguous memory.\n\u003e Unlike slices, arrays have a static length that cannot be changed after creation.\n\n## Basic Syntax\n\n```go\nvar arrayName [length]Type\n```\n\n## Array Declaration \u0026 Initialization\n\n### Zero-initialized Array\n\n```go\nvar arr [3]int\t// [0, 0, 0]\n```\n\n### Pre-filled Array\n\n```go\narr := [3]{1, 2, 3}\n```\n\n### Implicit Array (**...**)\n\n```go\narr := [...]{1, 2, 3, 4, 5}\t\t// length = 5\n```\n\n## Working with Arrays\n\n- ### Accessing Elements\n\n```go\narr := [3]int{1, 2, 3}\nfmt.Println(arr[1])  // 2\n```\n\n- ### Modifying Elements\n\n```go\narr[1] = 20\t\t// [1, 20, 3]\n```\n\n- ### Iteration\n\n```go\n// Using for-loop\nfor i := 0; i \u003c len(arr); i++ {\n    fmt.Println(arr[i])\n}\n\n// Using range\nfor index, value := range arr {\n    fmt.Printf(\"%d: %d\\n\", index, value)\n}\n```\n\n- ### Multidimensional Array\n\n```go\n matrix := [2][3]int{\n    {1, 2, 3},\n    {4, 5, 6},\n}\n\nfmt.Println(matrix[1][2])  // 6\n```\n\n- ### Matrix Operation\n\n```go\n func addMatrices(a, b [2][2]int) [2][2]int {\n    var result [2][2]int\n    for i := range a {\n        for j := range a[i] {\n            result[i][j] = a[i][j] + b[i][j]\n        }\n    }\n    return result\n}\n```\n\n[⬆️ Back to top](#top)\n\n---\n\n# Pointer\n\nPointers are a fundamental concept in Go that allow us to **directly manipulate memory addresses**.\nThey are essential for:\n\n- **Efficiently passing large data** (avoid copying)\n- **Modifying variables in functions**\n- **Working with data structures** (linked lists, trees)\n- **Interfacing with system-level code**\n\n## Pointer Terminology\n\n| Concept      | Description                                   |\n| ------------ | --------------------------------------------- |\n| `\u0026` operator | **Address-of** (gets the address of a value)  |\n| `*` operator | **Dereference** (gets the value at a pointer) |\n| `*Type`      | **Pointer to a given type**                   |\n\n## Pointer Syntax\n\nA pointer is a variable that stores the **memory address** of another variable.\n\n```go\nvar ptr *Type  // Declares a pointer to a Type\n```\n\n```go\npackage main\nimport \"fmt\"\n\nfunc print(numbers *[5]int) { // pointer to an array of 5 integers\n\tfmt.Println(numbers) // \u0026[1 2 3 4 5]\n}\n\nfunc main() {\n\tx := 10 \t// Only value hold | 10\n\tptr := \u0026x \t// Address of x | 0xc00000a0e8 | 824633759720\n\tval := *ptr // Value at address ptr | 10\n\t*ptr = 20 \t// Re-assign the value of x at the address of ptr | 20\n\n\tfmt.Println(\"Address of x = \", ptr)\t\t// 0xc00000a0e8\n\tfmt.Println(\"Value at address ptr = \", val)\t\t// 10\n\tfmt.Println(\"Final Value of x = \", x)\t// 20\n\n\t// Array print with the help of pointers\n\tarr := [5]int{1, 2, 3, 4, 5}\n\n\tprint(\u0026arr) // pass by reference\n}\n```\n\n## Pointer Mechanics:\n\n- ### Zero Value (**nil**)\n\n```go\nvar p *int\nfmt.Println(p == nil)  // true\n```\n\n```go\np := new(int)  // *int pointing to 0\n*p = 42        // Store 42 at the address\n```\n\n- ### Linked Data Structures\n\n```go\ntype Node struct {\n\tVal int\n\tNext *Node\t// Pointer to the next node\n}\n```\n\n[⬆️ Back to top](#top)\n\n---\n\n# Slice\n\n\u003e Slices are one of the most powerful and commonly used data structures in Go 🧠  \n\u003e Learn how slices work under the hood, how to use them effectively, and what to avoid.\n\n---\n\n## Slice Structure\n\nA slice is a **dynamic, flexible view** into an array. Unlike arrays, slices can:\n\n- Resize as needed\n- Reference only part of the underlying data\n- Share data without owning it\n\n### Slice Internal Structure:\n\n```go\ntype slice struct {\n    ptr  unsafe.Pointer\n    len  int\n    cap  int\n}\n```\n\n### 🔬 Slice Internal Fields\n\n- **`ptr`**: Points to the start of the underlying array segment.\n- **`len`**: Number of elements the slice currently holds.\n- **`cap`**: Total capacity from start pointer to the end of the array.\n\n\u003e 💡 Slices are reference types — copying a slice doesn't copy the data, just the reference.\n\n---\n\n## Creating Slices\n\n### Array to Slice\n\n- **`slice := arr[start(inclusive):end(exclusive)]`**\n- **`len = end - start`**\n- **`cap = len(arr) - start`**\n\n```go\narr := [5]int{1, 2, 3, 4, 5}\ns := arr[1:4]    // [2, 3, 4], len = 3, cap = 4\n```\n\n### Slice to Slice\n\n```go\ns1 := s[1:3]    // [3, 4], len = 2, cap = 3\n```\n\n- Still points to the same array memory\n- Cap is relative to original array\n\n### Slice Literals\n\n```go\ns := []int{1, 2, 3}    // [1, 2, 3], len = 3, cap = 3\n```\n\n- Creates slice with a backing array\n\n### Using **make()**\n\n- **`slice := make([]type, len)`**\n- **`slice := make([]type, len, cap)`**\n\n```go\ns := make([]int, 3) // [0, 0, 0], len = 3, cap = 3\n\ns := make([]int, 3, 5) // [0, 0, 0], len = 3, cap = 5\ns[0] = 5               // [5, 0, 0], len = 3, cap = 5\ns[2] = 10              // [5, 0, 10], len = 3, cap = 5\ns[3] = 20               // runtime error: index out of range [3] with length 3\n```\n\n- First form: len = cap\n- Second form: custom capacity\n\n### Nil Slice\n\n```go\nvar s []int  // [], ptr = nil, len = 0, cap = 0\n```\n\n- No memory allocated for the nil slice\n- Common in function return signatures\n\n### Empty Slice\n\n```go\ns := []int{}    // [], len = 0, cap = 0\ns := make([]int, 0)     // [], len = 0, cap = 0\n```\n\n- Yes, memory allocated for the empty slice\n- Used in APIs to return empty results\n\n---\n\n## Appending to Slices\n\n```go\nfunc main() {\n    var x []int     // [], ptr = nil, len = 0, cap = 0\n\n    x = append(x, 1)    // [1], len = 1, cap = 1\n    x = append(x, 2)    // [1, 2], len = 2, cap = 2\n    x = append(x, 3)    // [1, 2, 3], len = 3, cap = 4\n\n    y := x  // [1, 2, 3], len = 3, cap = 4 ; new slice (y) created and point to the (x) slice\n\n    x = append(x, 4)    // [1, 2, 3, 4], len = 4, cap = 4\n    y = append(y, 5)    // [1, 2, 3, 5], len = 4, cap = 4\n\n    x[0] = 10\n\n    fmt.Println(\"x = \", x, len(x), cap(x))  // [10, 2, 3, 5], len = 4, cap = 4\n    fmt.Println(\"y = \", y, len(y), cap(y))  // [10, 2, 3, 5], len = 4, cap = 4\n}\n```\n\n- ⚠️ Append might create a new array, but if cap is sufficient, both slices share memory!\n- **x** and **y** share memory until append() causes reallocation\n\nGo handles slice growth automatically with these rules:\n\n| Condition  | Growth Factor |\n| ---------- | ------------- |\n| cap ≤ 1024 | ×2            |\n| cap \u003e 1024 | ×1.25         |\n\n### Passing Slices to Functions\n\n```go\nfunc changesSlice(z []int) []int {\n\tz[0] = 10\n\tz = append(z, 11) // [10, 6, 7, 11], len = 4, cap = 6\n\treturn z\n}\n```\n\n### Memory Sharing Demonstration\n\n```go\nfunc main() {\n    x := []int{1, 2, 3, 4, 5}   // [1, 2, 3, 4, 5], len = 5, cap = 5\n\n    x = append(x, 6)    // [1, 2, 3, 4, 5, 6], len = 6, cap = 10\n    x = append(x, 7)    // [1, 2, 3, 4, 5, 6, 7], len = 7, cap = 10\n\n    a := x[4:]  // [5, 6, 7], len = 3, cap = 6\n\n    y := changesSlice(a)    // [10, 6, 7, 11], len = 4, cap = 6\n\n    fmt.Println(\"x = \", x, len(x), cap(x))  // [1, 2, 3, 4, 10, 6, 7], len = 7, cap = 10\n    fmt.Println(\"y = \", y, len(y), cap(y))  // [10, 6, 7, 11], len = 4, cap = 6\n\n    fmt.Println(\"x = \", x[0:8], len(x), cap(x))     // [1, 2, 3, 4, 10, 6, 7, 11], len = 7, cap = 10\n}\n```\n\n- Original array: [1, 2, 3, 4, 10, 6, 7, 11, _, _]\n\n---\n\n## Summary of Slice Creation\n\n| Method                  | Allocates Memory? | Description                    |\n| ----------------------- | ----------------- | ------------------------------ |\n| `arr[start:end]`        | No                | Slice of existing array        |\n| `s[start:end]`          | No                | Slice of slice (shares memory) |\n| `s []T{}` (empty slice) | Yes               | Empty but allocated            |\n| `make([]T, len)`        | Yes               | Allocates with length          |\n| `make([]T, len, cap)`   | Yes               | Allocates with custom capacity |\n| `var s []T` (nil slice) | No                | No allocation                  |\n\n[⬆️ Back to top](#top)\n\n---\n\n# Maps\n\nA **map** is an **unordered collection** of **key-value pairs** where:\n\n- Each key is unique\n- Values are accessed via keys\n- Keys must be comparable (`==` operator)\n\n## Map Syntax\n\n```go\nmap[KeyType]ValueType\n```\n\n## Declaring Maps\n\n- ### Using `make()` function\n\n```go\ndata := make(map[string]int)\n```\n\n- ### Using Map Literals\n\n```go\ndata := map[string]int{\n\t\"ali\": 24,\n\t\"anis\": 25,\n\t\"rakib\": 27,\n}\n```\n\n- ### Empty Map\n\n```go\nm := make(map[string]int)\t\t// Initialized but empty\nfmt.Println(m == nil)  \t\t\t// false\n```\n\n- ### Nil Map\n\n```go\nvar countries map[string]string\nfmt.Println(countries == nil)    \t// true\n```\n\n## Working with Map\n\n- ### Adding/Updating:\n\n```go\ndata[\"arif\"] = 25\ndata[\"ali\"] = 30\n```\n\n- ### Accessing\n\n```go\nmyAge := data[\"ali\"]\t// 30\n```\n\n- ### Deleting\n\n```go\ndelete(data, \"ali\")\n```\n\n- ### Check Length\n\n```go\ntotalData := len(data)\n```\n\n- ### Check If Key exists\n\n```go\nage, exists := data[\"arif\"]\nif exists {\n\tfmt.Println(\"Arif's age is: \", age)\n} else {\n\tfmt.Println(\"Arif's data is not found!\")\n}\n```\n\n- ### Shorter version\n\n```go\nif age, exists := data[\"arif\"]; exists {\n\tfmt.Println(age)\n}\n```\n\n- ### Reference Type Behavior\n\n```go\noriginal := map[string]int{\"x\": 1}\nref := original\nref[\"x\"] = 2\n\nfmt.Println(original[\"x\"]) // 2 (changed)\n```\n\n- ### Iteration over Map\n\n```go\nfor key, value := range data {\n\tfmt.Println(\"%s: %s\\n\", key, value)\n}\n\n// Values only\nfor _, value := range colors {\n    fmt.Println(value)\n}\n```\n\n- ### Nested Maps\n\n```go\nstudents := map[string]map[string]int{\n\t\t\"Akkas\": {\n\t\t\t\"Math\":    90,\n\t\t\t\"Physics\": 85,\n\t\t},\n\t\t\"Zidan\": {\n\t\t\t\"Math\":      90,\n\t\t\t\"Chemistry\": 87,\n\t\t},\n\t}\n\nfmt.Println(students[\"Akkas\"][\"Math\"])  \t// 90\n```\n\n## Practical Example (Word Frequency Counter)\n\n```go\nfunc wordCount(str string) map[string]int {\n\twords := strings.Fields(str)\n\tcounts := make(map[string]int)\n\n\tfor _, word := range words {\n\t\tcounts[word]++\n\t}\n\n\treturn counts\n}\n```\n\n## Map Properties\n\n- Keys must be of a type that supports `==` comparison (e.g., string, int).\n- Maps are **reference types** (passed by reference)\n- Not safe for concurrent use (use `sync.Map` for concurrency)\n\n[⬆️ Back to top](#top)\n\n---\n\n# Contributions\n\nContributions are welcome! Whether you're fixing bugs, improving documentation, or adding new Go examples — your help is appreciated.\n\n### How to Contribute\n\n1. 🍴 Fork the repository\n2. 📥 Clone your forked repo\n3. 🛠 Create a new branch (`git checkout -b feature-name`)\n4. 💻 Make your changes\n5. ✅ Commit your changes (`git commit -m \"Add new Go example\"`)\n6. 🔄 Push to the branch (`git push origin feature-name`)\n7. 📝 Create a Pull Request\n\nMake sure your code follows Go best practices and is properly documented. All PRs are reviewed before merging.\n\n---\n\n⭐ **Star** this repo if you found it helpful — it motivates future improvements!\n\n[⬆️ Back to top](#top)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faliakkas006%2Fgo-lang-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faliakkas006%2Fgo-lang-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faliakkas006%2Fgo-lang-basics/lists"}