← Back to Dashboard

Day 4: Advanced Features

Interfaces, Reflection, and Generics

1. Learn: Runtime Mechanics

2. Practice: Generic Stack & Reflection

Implement a generic Stack and a function that prints struct tags using reflection.

package main

import (
    "fmt"
    "reflect"
)

// Generic Stack
type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() (T, bool) {
    if len(s.items) == 0 {
        var zero T
        return zero, false
    }
    index := len(s.items) - 1
    item := s.items[index]
    s.items = s.items[:index]
    return item, true
}

// Reflection to read tags
type User struct {
    Name string `json:"name" validate:"required"`
    Age  int    `json:"age"`
}

func printTags(v interface{}) {
    t := reflect.TypeOf(v)
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        fmt.Printf("Field: %s, Tag: %s\n", field.Name, field.Tag.Get("json"))
    }
}

func main() {
    // Test Stack
    s := Stack[int]{}
    s.Push(10)
    s.Push(20)
    val, _ := s.Pop()
    fmt.Println("Popped:", val)

    // Test Reflection
    u := User{Name: "Alice", Age: 30}
    printTags(u)
}

3. Interview Questions

Q1: How is an interface value `nil` different from a `nil` pointer?

Answer: An interface is `nil` only if both its type and value are `nil`. If you store a `nil` pointer (e.g., `*int`) inside an interface, the interface is NOT `nil` because it holds the type `*int`.

Q2: Why is reflection slow?

Answer: It involves runtime type inspection, dynamic memory allocation, and prevents many compiler optimizations (like inlining). It should be used sparingly.

Q3: How do Go Generics affect binary size?

Answer: Go uses a hybrid approach (GCShape stenciling). It generates separate machine code for different underlying types (e.g., `int` vs `string`), which can increase binary size, but shares code for pointer types to mitigate bloat.

4. Revision (Day 2)

Recall: What happens if you cancel a parent Context?

Answer: All children contexts derived from it are also cancelled immediately. This propagates the cancellation signal down the call graph.

5. Assessment

Progress Log