Showing posts with label Golang. Show all posts
Showing posts with label Golang. Show all posts

Go (Golang) Data Types & Data Structures — Complete Guide

 

Go (Golang) Data Types & Data Structures — Complete Guide

Introduction

Go is a statically typed, compiled language designed for:

  • Simplicity

  • Performance

  • Concurrency

  • Predictable memory behavior

In Go:

  • Every variable has a fixed type

  • Types are checked at compile time

  • Zero values are automatically assigned

var x int // default value = 0 var s string // default value = ""

Categories of Go Data Types

Go data types can be grouped into:

  1. Basic Types

  2. Composite Types

  3. Reference Types

  4. Interface Types


1️⃣ Basic Data Types

a) Integer Types

var a int = 10 var b int64 = 100 var c uint = 20

Common integer types:

  • int, int8, int16, int32, int64

  • uint, uint8(byte), uint16, uint32, uint64

fmt.Println(a + 5)

b) Floating Point Types

var price float64 = 99.99 var temp float32 = -10.5
fmt.Println(price * 2)

c) Boolean

var isActive bool = true
if isActive { fmt.Println("Active user") }

d) String

var name string = "Vinod"

Strings are immutable in Go.

fmt.Println(name) fmt.Println(len(name))

Iterating characters:

for i, ch := range name { fmt.Println(i, string(ch)) }

2️⃣ Array (Fixed Size)

Arrays have fixed length.

var arr [3]int = [3]int{1, 2, 3}

Access:

fmt.Println(arr[0])

⚠️ Arrays are rarely used directly in Go.


3️⃣ Slice (MOST IMPORTANT)

Slices are dynamic, flexible views over arrays.

Create a slice

nums := []int{1, 2, 3}

Append

nums = append(nums, 4)

Access

fmt.Println(nums[0])

Update

nums[1] = 20

Iterate

for i, v := range nums { fmt.Println(i, v) }

Slice internals (Interview Gold)

A slice has:

pointer → array length capacity
fmt.Println(len(nums), cap(nums))

4️⃣ Map (Key–Value Store)

Maps store unordered key–value pairs.

Create map

user := map[string]int{ "age": 35, "score": 100, }

Add / Update

user["age"] = 36

Retrieve

age := user["age"]

Check existence

val, ok := user["city"] if !ok { fmt.Println("Key not found") }

Delete

delete(user, "score")

5️⃣ Struct (Custom Data Type)

Structs group related data.

type User struct { Name string Age int }

Create and use:

u := User{Name: "Vinod", Age: 35} fmt.Println(u.Name)

Pointer to struct:

pu := &u pu.Age = 36

6️⃣ List (container/list – Doubly Linked List)

Go provides a linked list via container/list.

import "container/list" l := list.New()

Add elements

l.PushBack(10) l.PushBack(20) l.PushFront(5)

Iterate

for e := l.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) }

Use cases:

  • Frequent insert/delete

  • No random access


7️⃣ Set (Using map)

Go has no built-in set, but maps are used.

set := make(map[int]bool)

Add

set[1] = true

Check

if set[1] { fmt.Println("Exists") }

Delete

delete(set, 1)

8️⃣ Pointer Types

Pointers store memory addresses.

x := 10 p := &x
fmt.Println(*p) // dereference

Used for:

  • Performance

  • Mutability

  • Struct updates

  • Large data passing


9️⃣ Interface (Polymorphism)

Interfaces define behavior.

type Speaker interface { Speak() string }

Implement interface:

type Person struct { Name string } func (p Person) Speak() string { return "Hello " + p.Name }

Use:

var s Speaker = Person{Name: "Vinod"} fmt.Println(s.Speak())

🔟 Zero Values (Very Important)

Go automatically assigns zero values.

TypeZero Value
int0
float0.0
boolfalse
string""
slicenil
mapnil
pointernil

1️⃣1️⃣ Mutable vs Immutable

TypeMutable
int, float, string
slice
map
struct
array❌ (value copy)

1️⃣2️⃣ Common Real-World Examples

List of users

users := []User{ {Name: "A", Age: 30}, {Name: "B", Age: 25}, }

Lookup by ID

usersMap := map[int]User{ 1: {Name: "A"}, }

Unique IDs

ids := make(map[int]struct{}) ids[100] = struct{}{}

1️⃣3️⃣ Summary Table

TypeBest Use
int / floatNumbers
stringText
arrayFixed size
sliceDynamic lists
mapFast lookup
structCustom objects
listFrequent inserts
interfacePolymorphism
pointerPerformance

1️⃣4️⃣ Interview One-Line Summary ⭐

Go provides strong, static data types with powerful composite structures like slices, maps, structs, and interfaces, enabling efficient, predictable, and concurrent-safe programs.

What Is Middleware in a Go Web Application?

 

What Is Middleware in a Go Web Application?

In Go’s built-in net/http package, middleware is a function that:

  • Wraps your main handler

  • Runs before the actual handler

  • Optionally runs after the handler

  • Adds cross-cutting features (logging, auth, tracing, monitoring)

Middleware is basically:

A function that intercepts an HTTP request before it reaches your handler.

Just like layers of an onion:

Client → Middleware → Handler → Response

⭐ Common Middleware Examples

  • Logging incoming requests

  • Authentication & authorization

  • Request validation

  • Setting headers

  • Rate limiting

  • Panic recovery

  • CORS handling

  • Request tracing (OpenTelemetry)


1️⃣ Text-Based Diagram: How Middleware Works

┌──────────────────────────┐ │ Client │ └───────────────▲──────────┘ │ request ▼ ┌───────────────────┐ │ Middleware │ ← logs, checks, sets headers └───────▲───────────┘ │ calls next() ▼ ┌─────────────────────┐ │ Handler │ ← business logic └─────────▲───────────┘ │ response ▼ ┌──────────────────────────┐ │ Client │ └──────────────────────────┘

2️⃣ Full Working Example: Go HTTP Server + Middleware + Handler + Resolver

We will build:

  • main.go → main entry

  • middleware.go → middleware

  • resolver.go → business resolver

  • handler.go → handler (controller)

  • Dockerfile → run as a container


📁 Folder Structure

go-middleware-demo/ │ ├── main.go ├── handler.go ├── resolver.go ├── middleware.go └── Dockerfile

3️⃣ Code: middleware.go

package main import ( "log" "net/http" "time" ) // LoggingMiddleware logs each incoming request. func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // BEFORE handler log.Printf("Incoming request → %s %s", r.Method, r.URL.Path) // Call next handler next.ServeHTTP(w, r) // AFTER handler log.Printf("Completed → %s %s (%v)", r.Method, r.URL.Path, time.Since(start)) }) }

4️⃣ Code: resolver.go (business logic layer)

package main // Resolver simulates fetching data or doing business logic. type Resolver struct{} func (r *Resolver) GetGreeting(name string) string { if name == "" { name = "Guest" } return "Hello, " + name + "! Welcome to Go Middleware Demo." }

5️⃣ Code: handler.go (HTTP handler)

package main import ( "encoding/json" "net/http" ) type Handler struct { Resolver *Resolver } func (h *Handler) GreetingHandler(w http.ResponseWriter, r *http.Request) { name := r.URL.Query().Get("name") message := h.Resolver.GetGreeting(name) resp := map[string]string{ "message": message, } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(resp) }

6️⃣ Code: main.go (server setup)

package main import ( "log" "net/http" ) func main() { resolver := &Resolver{} handler := &Handler{Resolver: resolver} mux := http.NewServeMux() mux.Handle("/greet", LoggingMiddleware(http.HandlerFunc(handler.GreetingHandler))) log.Println("Server started on port 8080") err := http.ListenAndServe(":8080", mux) if err != nil { log.Fatal(err) } }

7️⃣ Test the Server Locally

Run the app:

go run .

Test using browser or curl:

http://localhost:8080/greet?name=Vinod

Output:

{ "message": "Hello, Vinod! Welcome to Go Middleware Demo." }

Logs:

Incoming request → GET /greet Completed → GET /greet (1.2ms)

8️⃣ Add Docker Support (Dockerfile)

Create Dockerfile:

FROM golang:1.22-alpine AS build WORKDIR /app COPY . . RUN go mod init go-middleware-demo || true RUN go mod tidy RUN go build -o server . FROM alpine:3.19 WORKDIR /app COPY --from=build /app/server . EXPOSE 8080 CMD ["./server"]

9️⃣ Build & Run the Docker Container

Build:

docker build -t go-middleware-demo .

Run:

docker run -p 8080:8080 go-middleware-demo

Test:

http://localhost:8080/greet?name=Vinod

🔟 Text Diagram: Overall Architecture

┌────────────┐ │ Client │ └──────▲──────┘ │ ▼ ┌──────────────────────┐ │ Middleware │ │ - logging │ │ - authentication │ │ - rate limiting │ └─────────▲────────────┘ │ ▼ ┌──────────────────────┐ │ Handler │ │ - HTTP controller │ │ - calls resolver │ └─────────▲────────────┘ │ ▼ ┌──────────────────────┐ │ Resolver │ │ - business logic │ └──────────────────────┘

📝 Source code

https://github.com/kkvinodkumaran/go-middleware-demo 

 

📝 Summary (Interview-Ready)

✔ What is middleware in Go?

A function that wraps your handler to execute logic before/after request processing.

✔ What can middleware do?

  • Logging

  • Auth

  • Rate limiting

  • Setting headers

  • Error handling

  • Tracing

✔ Our example includes:

  • Logging middleware

  • Handler

  • Resolver

  • HTTP server

  • Dockerfile

     

      

Go Programming Style — Is Go OOP or Procedural? What Frameworks Does It Use?

 

Go Programming Style — Is Go OOP or Procedural? What Frameworks Does It Use?

Go (Golang) is a modern, fast, statically typed language created by Google.
But new developers often ask:

  • What kind of programming language is Go?

  • Is Go object-oriented?

  • Is Go procedural?

  • Does Go have classes?

  • What frameworks are popular in Go?

This blog explains Go’s design philosophy clearly.


1️⃣ What Is the Programming Style of Go?

Go is a multi-paradigm language with influences from:

  • Procedural programming (like C)

  • Object-oriented programming (like Java)

  • Functional programming (partial features)

  • Concurrency-first programming (goroutines & channels)

But Go does not fully belong to any one category.

The best description is:

Go is a procedural language with lightweight object-oriented features and built-in concurrency.

Let’s break this down.


2️⃣ Is Go Object-Oriented?

✔ Yes and No.

Go does not have:

❌ Classes
❌ Inheritance
❌ Constructors
❌ Overloading
❌ Traditional OOP hierarchy

But Go does have:

✔ Structs
✔ Methods on structs
✔ Encapsulation (exported/unexported)
✔ Interfaces (implicit!)
✔ Composition instead of inheritance

So Go supports object-oriented design, but without the heavy OOP complexity found in Java/C++.

Example: Methods on Struct (OOP-style)

type User struct { Name string } func (u User) Greet() string { return "Hello, " + u.Name }

Key Difference:

  • Go has no class keyword

  • Methods belong to structs implicitly

  • Interfaces are satisfied automatically (no implements keyword)

Go’s OOP philosophy:

Composition over inheritance
Interfaces over abstract classes

This makes Go simpler and more flexible.


3️⃣ Is Go Procedural?

✔ Yes, Go is strongly procedural.

Go supports:

✔ Top-level functions
✔ Packages as modules
✔ Simple flow control (if, for, switch)
✔ Straightforward function calls
✔ No hidden magic

Example:

func add(a, b int) int { return a + b }

This procedural nature keeps Go code readable and predictable.


4️⃣ Is Go Functional?

Go includes some functional features:

✔ First-class functions
✔ Passing functions as parameters
✔ Returning functions
✔ Lambdas/anonymous functions

Example:

fn := func(x int) int { return x * 2 } result := fn(5)

But Go is not a full functional language — no immutability guarantees, no pattern matching.


5️⃣ Go’s Unique Strength: Concurrency-First Design

One of Go’s main programming styles is built-in concurrency:

  • Goroutines (lightweight threads)

  • Channels (communication mechanism)

  • Select statements

Example:

go func() { fmt.Println("Hello from goroutine") }()

This is what makes Go ideal for cloud systems, servers, distributed systems, and microservices.


📝 Summary: What Style Is Go?

FeatureGo SupportNotes
Procedural✔ YesVery strong
Object-Oriented✔ PartiallyNo classes; uses structs + methods
Functional✔ PartiallyFunctions are first-class
Concurrent✔ NativeGoroutines, channels
Generic✔ Yes (Go 1.18+)Adds type safety

Go = procedural + composition-based OOP + native concurrency


6️⃣ Top Frameworks & Libraries in Golang

Go has a rich ecosystem. Here are the most popular frameworks used across the industry.


1. Web Frameworks

Gin (Most Popular)

Fast, lightweight, great for REST APIs.
https://github.com/gin-gonic/gin

Fiber

Express.js-style, extremely fast.
https://github.com/gofiber/fiber

Echo

Minimal, fast, clean.
https://github.com/labstack/echo

Chi

Idiomatic, lightweight, flexible.
https://github.com/go-chi/chi

Beego

Full-featured MVC framework.
https://github.com/beego/beego


2. Microservices Frameworks

Go-Kit

Enterprise microservice toolkit (Netflix-style).
https://github.com/go-kit/kit

Go-Micro

Tools for service discovery, RPC, configuration.
https://github.com/asim/go-micro

Kratos (Bilibili)

For large distributed systems.
https://github.com/go-kratos/kratos


3. RPC / gRPC Frameworks

gRPC (official)

High-performance RPC with protobuf.
https://github.com/grpc/grpc-go

Connect RPC

Simpler alternative to gRPC.
https://github.com/connectrpc/connect-go


4. Database Libraries

GORM

Most popular ORM for Go.
https://gorm.io/

SQLX

A thin wrapper over database/sql.
https://github.com/jmoiron/sqlx

Ent (Facebook)

Schema-based ORM with code generation.
https://entgo.io/


5. Concurrent / Distributed Systems Libraries

Go-Redis

High-performance Redis client.

NATS

Messaging system for microservices.

Kafka clients

Sarama, Confluent-Kafka-Go, Segmentio.


6. Testing Frameworks

Testify

Most popular testing framework.

Ginkgo + Gomega

BDD-style testing.


Summary (Interview-Ready)

✔ What is Go’s programming style?

Go is a procedural language with lightweight OOP features and built-in concurrency.

✔ Is Go object-oriented?

Yes, but without classes or inheritance.
Go uses structs + methods + interfaces.

✔ Is Go procedural?

Yes, strongly procedural.

✔ Is Go functional?

Partially.

✔ Top frameworks in Go?

  • Web: Gin, Fiber, Echo, Chi, Beego

  • Microservices: Go-Kit, Go-Micro, Kratos

  • RPC: gRPC, Connect RPC

  • ORM: GORM, SQLX, Ent

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts