Interfaces, Reflection, and Generics
(type, value).
iface: For interfaces with methods. Contains a pointer to the itab (interface table) and the data.eface: For interface{} (empty interface). Contains type info and data.reflect package allows inspecting types and values at runtime. Useful for serialization (JSON) and ORMs, but has a performance cost and loses compile-time safety.[T any]. Monomorphization (stenciling) creates specialized versions of the code at compile time (mostly).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)
}
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`.
Answer: It involves runtime type inspection, dynamic memory allocation, and prevents many compiler optimizations (like inlining). It should be used sparingly.
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.
Answer: All children contexts derived from it are also cancelled immediately. This propagates the cancellation signal down the call graph.