Go Language Fundamentals

Master Go programming with visual diagrams, data flow charts, and comprehensive examples covering concurrency, channels, and best practices

Go (Golang) is an open-source programming language developed by Google, designed for building scalable, high-performance applications with built-in concurrency support.

Go Architecture Overview

graph TB
    A[Go Source Code] --> B[Go Compiler]
    B --> C[Native Binary]
    C --> D[Operating System]
    
    E[Go Runtime] --> F[Goroutine Scheduler]
    E --> G[Garbage Collector]
    E --> H[Memory Manager]
    
    F --> I[Concurrent Execution]
    G --> J[Automatic Memory]
    H --> K[Efficient Allocation]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style E fill:#9C27B0

Key Points:

  • Compiled Language: Go compiles directly to native machine code for fast execution
  • Go Runtime: Manages goroutines, garbage collection, and memory automatically
  • Single Binary: Produces standalone executables with no external dependencies
  • Cross-Platform: Compile for different OS/architectures from single codebase
  • Fast Compilation: Compiles large codebases in seconds, enabling rapid development

Package System Architecture

graph LR
    A[main Package] --> B[Entry Point]
    B --> C[func main]
    
    D[Library Packages] --> E[utils]
    D --> F[models]
    D --> G[handlers]
    
    A --> H[Import Packages]
    H --> E
    H --> F
    H --> G
    
    style A fill:#2196F3
    style D fill:#4CAF50
    style H fill:#FF9800

Key Points:

  • main Package: Special package that defines program entry point with main() function
  • Library Packages: Reusable code organized by functionality (utils, models, handlers)
  • Import System: Use import statement to access code from other packages
  • Package Naming: Use lowercase, short, descriptive names without underscores
  • Visibility: Capitalized names are exported (public), lowercase are private

Variable Declaration Flow

flowchart TB
    A[Variable Declaration] --> B{Declaration Type}
    
    B -->|var| C[var name type = value]
    B -->|Short| D[name := value]
    B -->|const| E[const name = value]
    
    C --> F[Explicit Type]
    D --> G[Type Inference]
    E --> H[Immutable]
    
    F --> I[Compile Time Check]
    G --> I
    H --> I
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0
    style E fill:#F44336

Key Points:

  • var Keyword: Explicit type declaration, can be used at package or function level
  • Short Declaration (:=): Type inference, only inside functions, most common
  • const Keyword: Compile-time constants, immutable values
  • Zero Values: Variables without initialization get default values (0, false, "", nil)

Data Types Hierarchy

graph TB
    A[Go Data Types] --> B[Basic Types]
    A --> C[Composite Types]
    A --> D[Reference Types]
    
    B --> B1[int, int8, int16, int32, int64]
    B --> B2[uint, uint8, uint16, uint32, uint64]
    B --> B3[float32, float64]
    B --> B4[bool, string, byte, rune]
    
    C --> C1[Array - Fixed Size]
    C --> C2[Struct - Custom Types]
    
    D --> D1[Slice - Dynamic Array]
    D --> D2[Map - Key-Value]
    D --> D3[Channel - Communication]
    D --> D4[Pointer - Memory Address]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0

Key Points:

  • Basic Types: Primitive types for numbers, booleans, and strings
  • Composite Types: Arrays and structs with fixed structure and size
  • Reference Types: Slices, maps, channels, pointers that reference underlying data
  • Type Safety: Strong static typing prevents type-related errors at compile time
  • Type Conversion: Explicit conversion required between different types

Function Execution Flow

sequenceDiagram
    participant Caller
    participant Function
    participant Return
    
    Caller->>Function: Pass Arguments
    Function->>Function: Execute Logic
    Function->>Function: Process Data
    Function->>Return: Multiple Values
    Return->>Caller: result, error
    
    Note over Function: Named Returns
    Note over Return: Error Handling

Key Points:

  • Multiple Returns: Functions can return multiple values, commonly (result, error)
  • Named Returns: Pre-declare return variables for cleaner code
  • Variadic Functions: Accept variable number of arguments using ...Type
  • First-Class Functions: Functions are values, can be assigned and passed around

Control Flow Patterns

flowchart TB
    A[Control Statements] --> B[if/else]
    A --> C[switch]
    A --> D[for loop]
    
    B --> B1[Condition Check]
    B --> B2[Short Statement]
    
    C --> C1[Expression Switch]
    C --> C2[Type Switch]
    C --> C3[No Condition]
    
    D --> D1[Traditional Loop]
    D --> D2[While-style]
    D --> D3[Range Loop]
    D --> D4[Infinite Loop]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0

Key Points:

  • if Statement: Can include short statement before condition (if x := getValue(); x > 0)
  • switch: No fallthrough by default, can switch on types or expressions
  • for Loop: Only loop construct in Go, versatile for all iteration needs
  • range: Iterate over slices, arrays, maps, strings, and channels

Struct and Method Architecture

graph TB
    A[Struct Definition] --> B[Fields]
    A --> C[Methods]
    
    B --> B1[Data Members]
    B --> B2[Embedded Structs]
    
    C --> C1[Value Receiver]
    C --> C2[Pointer Receiver]
    
    C1 --> D[Read-Only Operations]
    C2 --> E[Modify State]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0
    style E fill:#F44336

Key Points:

  • Structs: Custom types that group related data fields together
  • Methods: Functions with receiver argument, attached to types
  • Value Receiver: Method receives copy, cannot modify original struct
  • Pointer Receiver: Method can modify original struct, more efficient for large structs
  • Embedding: Compose structs by embedding other structs for code reuse

Interface System

graph LR
    A[Interface] --> B[Method Set]
    B --> C[Implementation]
    
    D[Type 1] --> C
    E[Type 2] --> C
    F[Type 3] --> C
    
    C --> G[Polymorphism]
    G --> H[Flexible Code]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style G fill:#9C27B0

Key Points:

  • Implicit Implementation: Types implement interfaces automatically by having required methods
  • Empty Interface: interface{} (or any) accepts any type, used for generic programming
  • Type Assertion: Extract concrete type from interface value
  • Polymorphism: Write functions that work with any type implementing interface

Goroutine Concurrency Model

sequenceDiagram
    participant Main
    participant G1 as Goroutine 1
    participant G2 as Goroutine 2
    participant G3 as Goroutine 3
    
    Main->>G1: go func()
    Main->>G2: go func()
    Main->>G3: go func()
    
    par Concurrent Execution
        G1->>G1: Execute Task 1
        G2->>G2: Execute Task 2
        G3->>G3: Execute Task 3
    end
    
    G1->>Main: Complete
    G2->>Main: Complete
    G3->>Main: Complete

Key Points:

  • Lightweight: Goroutines use ~2KB stack, can run millions concurrently
  • go Keyword: Prefix function call with 'go' to run it concurrently
  • Scheduler: Go runtime multiplexes goroutines onto OS threads efficiently
  • Non-Blocking: Main function doesn't wait for goroutines unless synchronized

Channel Communication Flow

flowchart LR
    A[Goroutine 1] -->|Send Data| B[Channel]
    B -->|Receive Data| C[Goroutine 2]
    
    D[Producer] -->|ch <- value| E[Buffered Channel]
    E -->|value := <-ch| F[Consumer]
    
    G[Select] --> H[Channel 1]
    G --> I[Channel 2]
    G --> J[Timeout]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0
    style E fill:#F44336
    style F fill:#00BCD4

Key Points:

  • Synchronization: Channels provide safe communication between goroutines
  • Unbuffered: Send blocks until receive, receive blocks until send
  • Buffered: Can hold N values before blocking, specified at creation
  • Select Statement: Wait on multiple channel operations simultaneously
  • Close: Sender closes channel to signal no more values coming

Error Handling Pattern

flowchart TB
    A[Function Call] --> B{Error Check}
    B -->|err != nil| C[Handle Error]
    B -->|err == nil| D[Continue Execution]
    
    C --> E[Log Error]
    C --> F[Return Error]
    C --> G[Retry Logic]
    
    D --> H[Use Result]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#F44336
    style D fill:#00BCD4

Key Points:

  • Explicit Errors: Functions return error as last return value
  • Error Interface: Any type with Error() string method implements error
  • Check Immediately: Always check error before using result
  • Error Wrapping: Use fmt.Errorf with %w to wrap errors with context

Memory Management

graph TB
    A[Memory Allocation] --> B[Stack]
    A --> C[Heap]
    
    B --> B1[Local Variables]
    B --> B2[Function Parameters]
    B --> B3[Fast Allocation]
    
    C --> C1[Dynamic Data]
    C --> C2[Pointers]
    C --> C3[Garbage Collected]
    
    D[GC] --> E[Mark Phase]
    E --> F[Sweep Phase]
    F --> G[Free Memory]
    
    style A fill:#2196F3
    style B fill:#4CAF50
    style C fill:#FF9800
    style D fill:#9C27B0

Key Points:

  • Stack Allocation: Fast, automatic cleanup when function returns
  • Heap Allocation: For data that outlives function scope or is too large
  • Escape Analysis: Compiler determines if variable can stay on stack
  • Garbage Collection: Automatic memory management, concurrent GC minimizes pauses

Quick Reference

Essential Commands

go run main.go          # Run program
go build               # Compile binary
go test                # Run tests
go mod init module     # Initialize module
go get package         # Download dependency

Common Patterns

  • Error Handling: Always check errors immediately
  • Defer: Use for cleanup (close files, unlock mutexes)
  • Interfaces: Design with small, focused interfaces
  • Goroutines: Use channels for communication, not shared memory