Golang Reflection Quiz

Golang
0 Passed
0% acceptance

35 comprehensive questions on Golang's reflection capabilities, covering reflect.Type & reflect.Value usage, value modification, kind checking, performance considerations, and when to avoid reflection — with 15 code examples demonstrating practical reflection techniques.

35 Questions
~70 minutes
1

Question 1

What is reflection in Go?

go
import "reflect"

type User struct {
    Name string
    Age  int
}

func main() {
    u := User{Name: "Alice", Age: 30}
    v := reflect.ValueOf(u)
    t := reflect.TypeOf(u)
    
    fmt.Println("Type:", t.Name())
    fmt.Println("Kind:", t.Kind())
    fmt.Println("Fields:", t.NumField())
}
A
Runtime type inspection and manipulation using reflect package
B
Compile-time type checking
C
Memory allocation
D
No reflection in Go
2

Question 2

How do you get reflect.Type from a value?

go
var x int = 42

t := reflect.TypeOf(x)
fmt.Println("Type:", t)
fmt.Println("Name:", t.Name())
fmt.Println("Kind:", t.Kind())

// For pointers
var p *int
t2 := reflect.TypeOf(p)
fmt.Println("Pointer type:", t2)
fmt.Println("Elem type:", t2.Elem())
A
Use reflect.TypeOf(value)
B
Use reflect.ValueOf(value).Type()
C
Use typeof(value)
D
Cannot get type at runtime
3

Question 3

How do you get reflect.Value from a value?

go
s := "hello"
v := reflect.ValueOf(s)

fmt.Println("Value:", v)
fmt.Println("Type:", v.Type())
fmt.Println("Kind:", v.Kind())
fmt.Println("String:", v.String())

// For interface{}
var i interface{} = 42
v2 := reflect.ValueOf(i)
fmt.Println("Interface value:", v2.Interface())
A
Use reflect.ValueOf(value)
B
Use reflect.TypeOf(value).Value()
C
Use valueOf(value)
D
Cannot get value reflection
4

Question 4

How do you check if a reflect.Value is valid?

go
var v reflect.Value
fmt.Println("Valid:", v.IsValid())  // false

v = reflect.ValueOf(42)
fmt.Println("Valid:", v.IsValid())  // true

// Zero Value
var zero reflect.Value
fmt.Println("Zero valid:", zero.IsValid())  // false
A
Use v.IsValid() method
B
Use v != nil
C
Use v.IsNil()
D
Cannot check validity
5

Question 5

How do you get the underlying value from reflect.Value?

go
i := 42
v := reflect.ValueOf(i)

// Get as interface{}
val := v.Interface()
fmt.Println("Interface:", val)

// Type assert back
original := val.(int)
fmt.Println("Original:", original)

// For strings
s := "hello"
v2 := reflect.ValueOf(s)
str := v2.Interface().(string)
fmt.Println("String:", str)
A
Use v.Interface() and type assert
B
Use v.Value()
C
Use v.Get()
D
Cannot get underlying value
6

Question 6

How do you check the Kind of a reflect.Type?

go
var x int
v := reflect.ValueOf(x)

t := v.Type()
fmt.Println("Type:", t)
fmt.Println("Kind:", t.Kind())

// Different kinds
fmt.Println("Int kind:", reflect.TypeOf(42).Kind())
fmt.Println("String kind:", reflect.TypeOf("").Kind())
fmt.Println("Slice kind:", reflect.TypeOf([]int{}).Kind())
fmt.Println("Struct kind:", reflect.TypeOf(struct{}{}).Kind())
A
Use t.Kind() which returns reflect.Kind
B
Use t.Type()
C
Use typeof(t)
D
Cannot check kind
7

Question 7

How do you iterate over struct fields using reflection?

go
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

p := Person{Name: "Alice", Age: 30}
v := reflect.ValueOf(p)
t := reflect.TypeOf(p)

for i := 0; i < v.NumField(); i++ {
    field := v.Field(i)
    fieldType := t.Field(i)
    
    fmt.Printf("Field %d: %s = %v (tag: %s)\n",
        i, fieldType.Name, field.Interface(), fieldType.Tag)
}
A
Use v.NumField() and v.Field(i) to iterate
B
Use for range on struct
C
Use v.Fields()
D
Cannot iterate struct fields
8

Question 8

How do you modify a value using reflection?

go
func setValue(v reflect.Value, newVal interface{}) {
    if v.CanSet() {
        v.Set(reflect.ValueOf(newVal))
    } else {
        fmt.Println("Cannot set value")
    }
}

func main() {
    x := 42
    v := reflect.ValueOf(&x).Elem()  // Get pointer to modify
    
    if v.CanSet() {
        v.SetInt(100)
        fmt.Println("New value:", x)  // 100
    }
}
A
Use v.Set() or v.SetInt() etc., but only if v.CanSet() is true
B
Use v.Modify()
C
Use v.Change()
D
Cannot modify values with reflection
9

Question 9

How do you check if a reflect.Value can be set?

go
x := 42
v1 := reflect.ValueOf(x)
fmt.Println("Can set direct:", v1.CanSet())  // false

v2 := reflect.ValueOf(&x).Elem()
fmt.Println("Can set pointer elem:", v2.CanSet())  // true

// Struct field
s := struct{ A int }{42}
v3 := reflect.ValueOf(&s).Elem().Field(0)
fmt.Println("Can set struct field:", v3.CanSet())  // true
A
Use v.CanSet() which returns true for addressable values
B
Use v.IsValid()
C
Use v.CanAddr()
D
Cannot check
10

Question 10

How do you call a function using reflection?

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

func main() {
    fn := reflect.ValueOf(add)
    
    args := []reflect.Value{
        reflect.ValueOf(10),
        reflect.ValueOf(20),
    }
    
    result := fn.Call(args)
    fmt.Println("Result:", result[0].Interface())  // 30
}
A
Use fn.Call([]reflect.Value{...})
B
Use fn.Invoke()
C
Use reflect.Call(fn)
D
Cannot call functions with reflection
11

Question 11

How do you create a new value using reflection?

go
t := reflect.TypeOf(42)

// Create zero value
v1 := reflect.New(t)
fmt.Println("Zero value:", v1.Interface())  // *int pointing to 0

// Create slice
t2 := reflect.TypeOf([]int{})
v2 := reflect.MakeSlice(t2, 0, 10)
fmt.Println("Slice:", v2.Interface())  // []

// Create map
t3 := reflect.TypeOf(map[string]int{})
v3 := reflect.MakeMap(t3)
fmt.Println("Map:", v3.Interface())  // map[]
A
Use reflect.New(), reflect.MakeSlice(), reflect.MakeMap() etc.
B
Use reflect.Create()
C
Use new() with reflection
D
Cannot create values with reflection
12

Question 12

How do you handle struct tags with reflection?

go
type Config struct {
    Host     string `json:"host" validate:"required"`
    Port     int    `json:"port" validate:"min=1,max=65535"`
    Timeout  time.Duration `json:"timeout"`
}

c := Config{}
t := reflect.TypeOf(c)

for i := 0; i < t.NumField(); i++ {
    field := t.Field(i)
    jsonTag := field.Tag.Get("json")
    validateTag := field.Tag.Get("validate")
    
    fmt.Printf("Field: %s, JSON: %s, Validate: %s\n",
        field.Name, jsonTag, validateTag)
}
A
Use field.Tag.Get("tagname") to access struct tags
B
Use field.Tags()
C
Use reflect.Tags()
D
Cannot access struct tags
13

Question 13

How do you check if a type implements an interface?

go
type Writer interface {
    Write([]byte) (int, error)
}

type MyWriter struct{}

func (w *MyWriter) Write(data []byte) (int, error) {
    return len(data), nil
}

func main() {
    t := reflect.TypeOf((*MyWriter)(nil))
    writerType := reflect.TypeOf((*Writer)(nil)).Elem()
    
    fmt.Println("Implements Writer:", t.Implements(writerType))
    
    // Or check method
    method, ok := t.MethodByName("Write")
    fmt.Println("Has Write method:", ok)
}
A
Use t.Implements(interfaceType)
B
Use t.IsInterface()
C
Use instanceof(t)
D
Cannot check interface implementation
14

Question 14

How do you get method information using reflection?

go
type Calculator struct{}

func (c Calculator) Add(a, b int) int {
    return a + b
}

func main() {
    t := reflect.TypeOf(Calculator{})
    
    method, ok := t.MethodByName("Add")
    if ok {
        fmt.Println("Method:", method.Name)
        fmt.Println("Type:", method.Type)
        fmt.Println("Inputs:", method.Type.NumIn())
        fmt.Println("Outputs:", method.Type.NumOut())
    }
    
    // All methods
    for i := 0; i < t.NumMethod(); i++ {
        m := t.Method(i)
        fmt.Println("Method", i, ":", m.Name)
    }
}
A
Use t.MethodByName() and t.NumMethod()
B
Use t.Methods()
C
Use reflect.Methods(t)
D
Cannot get method information
15

Question 15

How do you handle slice reflection operations?

go
s := []int{1, 2, 3}
v := reflect.ValueOf(s)

fmt.Println("Len:", v.Len())
fmt.Println("Cap:", v.Cap())

// Get element
fmt.Println("Element 0:", v.Index(0).Interface())

// Append
newSlice := reflect.Append(v, reflect.ValueOf(4))
fmt.Println("Appended:", newSlice.Interface())

// Set element (if addressable)
s2 := []int{1, 2, 3}
v2 := reflect.ValueOf(&s2).Elem()
v2.Index(0).SetInt(99)
fmt.Println("Modified:", s2)
A
Use v.Len(), v.Index(), reflect.Append() for operations
B
Use v.Slice()
C
Use slice operations directly
D
Cannot handle slices with reflection
16

Question 16

How do you handle map reflection operations?

go
m := map[string]int{"a": 1, "b": 2}
v := reflect.ValueOf(m)

// Get keys
keys := v.MapKeys()
for _, key := range keys {
    value := v.MapIndex(key)
    fmt.Printf("%s: %v\n", key.Interface(), value.Interface())
}

// Set value
m2 := map[string]int{}
v2 := reflect.ValueOf(&m2).Elem()
key := reflect.ValueOf("newkey")
val := reflect.ValueOf(42)
v2.SetMapIndex(key, val)
fmt.Println("Map:", m2)
A
Use v.MapKeys(), v.MapIndex(), v.SetMapIndex()
B
Use v.Keys()
C
Use map operations directly
D
Cannot handle maps with reflection
17

Question 17

What are the performance implications of reflection?

A
Reflection is much slower than direct operations due to runtime type checking and boxing/unboxing
B
Reflection is faster than direct operations
C
No performance difference
D
Reflection improves performance
18

Question 18

How do you implement a generic function using reflection?

go
func printTypeAndValue(x interface{}) {
    t := reflect.TypeOf(x)
    v := reflect.ValueOf(x)
    
    fmt.Printf("Type: %s, Value: %v\n", t, v.Interface())
}

func main() {
    printTypeAndValue(42)
    printTypeAndValue("hello")
    printTypeAndValue([]int{1, 2, 3})
}
A
Use interface{} parameters and reflect.TypeOf/reflect.ValueOf
B
Use generics (Go 1.18+)
C
Use type assertions
D
Cannot implement generic functions
19

Question 19

How do you handle pointer types with reflection?

go
x := 42
p := &x

v := reflect.ValueOf(p)
fmt.Println("Type:", v.Type())  // *int
fmt.Println("Kind:", v.Kind())  // ptr

// Dereference
elem := v.Elem()
fmt.Println("Elem type:", elem.Type())  // int
fmt.Println("Elem value:", elem.Interface())  // 42

// Modify through pointer
if elem.CanSet() {
    elem.SetInt(100)
    fmt.Println("Modified x:", x)  // 100
}
A
Use v.Elem() to dereference pointers
B
Use v.Deref()
C
Use *v
D
Cannot handle pointers
20

Question 20

How do you implement deep equality using reflection?

go
func deepEqual(a, b interface{}) bool {
    va := reflect.ValueOf(a)
    vb := reflect.ValueOf(b)
    
    return reflect.DeepEqual(va.Interface(), vb.Interface())
}

func main() {
    a := []int{1, 2, 3}
    b := []int{1, 2, 3}
    
    fmt.Println("Equal:", deepEqual(a, b))  // true
    
    // Or use reflect.DeepEqual directly
    fmt.Println("Direct:", reflect.DeepEqual(a, b))  // true
}
A
Use reflect.DeepEqual() for deep comparison
B
Use == operator
C
Use reflect.Equal()
D
Cannot compare deeply
21

Question 21

How do you check if a field is exported using reflection?

go
type Person struct {
    Name string  // exported
    age  int     // unexported
}

p := Person{Name: "Alice", age: 30}
t := reflect.TypeOf(p)

for i := 0; i < t.NumField(); i++ {
    field := t.Field(i)
    fmt.Printf("Field %s: Exported = %t\n",
        field.Name, field.PkgPath == "")
}
A
Check if field.PkgPath == "" (empty for exported fields)
B
Check field.IsExported()
C
Check field.Public
D
Cannot check if exported
22

Question 22

How do you implement a simple JSON marshaler using reflection?

go
func simpleMarshal(v interface{}) ([]byte, error) {
    val := reflect.ValueOf(v)
    typ := reflect.TypeOf(v)
    
    if typ.Kind() != reflect.Struct {
        return nil, fmt.Errorf("only structs supported")
    }
    
    result := make(map[string]interface{})
    for i := 0; i < val.NumField(); i++ {
        field := val.Field(i)
        fieldType := typ.Field(i)
        
        if fieldType.PkgPath != "" {
            continue  // skip unexported
        }
        
        tag := fieldType.Tag.Get("json")
        name := fieldType.Name
        if tag != "" {
            name = tag
        }
        
        result[name] = field.Interface()
    }
    
    return json.Marshal(result)
}
A
Iterate struct fields, handle tags, build map, marshal to JSON
B
Use json.Marshal directly
C
Use fmt.Sprintf
D
Cannot implement JSON marshaler
23

Question 23

How do you handle channel types with reflection?

go
ch := make(chan int, 5)
v := reflect.ValueOf(ch)

t := v.Type()
fmt.Println("Type:", t)  // chan int
fmt.Println("Kind:", t.Kind())  // chan
fmt.Println("Elem type:", t.Elem())  // int

// Send
v.Send(reflect.ValueOf(42))

// Receive
result, ok := v.Recv()
fmt.Println("Received:", result.Interface(), "ok:", ok)

// Close
v.Close()
A
Use v.Send(), v.Recv(), v.Close() for channel operations
B
Use v.Chan()
C
Use channel operations directly
D
Cannot handle channels with reflection
24

Question 24

How do you implement a type switch using reflection?

go
func typeSwitch(v interface{}) string {
    switch reflect.TypeOf(v).Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        return "integer"
    case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        return "unsigned integer"
    case reflect.Float32, reflect.Float64:
        return "float"
    case reflect.String:
        return "string"
    case reflect.Bool:
        return "boolean"
    case reflect.Slice:
        return "slice"
    case reflect.Map:
        return "map"
    default:
        return "other"
    }
}

func main() {
    fmt.Println(typeSwitch(42))        // integer
    fmt.Println(typeSwitch("hello"))  // string
    fmt.Println(typeSwitch([]int{}))  // slice
}
A
Use reflect.TypeOf(v).Kind() in switch statement
B
Use type switch syntax
C
Use v.Kind()
D
Cannot implement type switch
25

Question 25

How do you handle interface{} values with reflection?

go
func processInterface(v interface{}) {
    val := reflect.ValueOf(v)
    
    if val.Kind() == reflect.Interface {
        // Unwrap interface
        elem := val.Elem()
        fmt.Println("Interface contains:", elem.Type())
        
        if elem.IsValid() {
            processValue(elem)
        }
    } else {
        processValue(val)
    }
}

func processValue(v reflect.Value) {
    fmt.Printf("Type: %s, Value: %v\n", v.Type(), v.Interface())
}
A
Use v.Elem() to unwrap interface{} values
B
Use v.Interface()
C
Use type assertion
D
Cannot handle interface{}
26

Question 26

What are the main performance costs of reflection?

A
Boxing/unboxing, runtime type checking, method dispatch overhead, memory allocation
B
No performance costs
C
Faster than direct calls
D
Only CPU overhead
27

Question 27

How do you implement a simple ORM using reflection?

go
type Model struct {
    ID   int    `db:"id"`
    Name string `db:"name"`
}

func (m *Model) Save() error {
    t := reflect.TypeOf(*m)
    v := reflect.ValueOf(*m)
    
    fields := make(map[string]interface{})
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        value := v.Field(i)
        
        tag := field.Tag.Get("db")
        if tag == "" {
            continue
        }
        
        fields[tag] = value.Interface()
    }
    
    // Simulate database insert
    return insertIntoDB(t.Name(), fields)
}
A
Iterate struct fields, extract db tags, build field map for database operations
B
Use direct SQL
C
Use fmt.Sprintf
D
Cannot implement ORM
28

Question 28

How do you handle recursive types with reflection?

go
type Node struct {
    Value int
    Left  *Node
    Right *Node
}

func printTree(n *Node, depth int) {
    if n == nil {
        return
    }
    
    indent := strings.Repeat("  ", depth)
    fmt.Printf("%sValue: %d\n", indent, n.Value)
    
    if n.Left != nil {
        fmt.Printf("%sLeft:\n", indent)
        printTree(n.Left, depth+1)
    }
    
    if n.Right != nil {
        fmt.Printf("%sRight:\n", indent)
        printTree(n.Right, depth+1)
    }
}

// Using reflection
func printTreeReflect(v reflect.Value, depth int) {
    if !v.IsValid() || v.IsNil() {
        return
    }
    
    indent := strings.Repeat("  ", depth)
    
    // Get Value field
    valueField := v.Elem().FieldByName("Value")
    fmt.Printf("%sValue: %v\n", indent, valueField.Interface())
    
    // Recurse on Left and Right
    leftField := v.Elem().FieldByName("Left")
    if !leftField.IsNil() {
        fmt.Printf("%sLeft:\n", indent)
        printTreeReflect(leftField, depth+1)
    }
    
    rightField := v.Elem().FieldByName("Right")
    if !rightField.IsNil() {
        fmt.Printf("%sRight:\n", indent)
        printTreeReflect(rightField, depth+1)
    }
}
A
Use recursive reflection calls with proper nil checking
B
Use direct recursion
C
Use loops
D
Cannot handle recursive types
29

Question 29

How do you implement validation using reflection?

go
type Validator struct {
    Rules map[string][]string
}

func (v *Validator) Validate(s interface{}) []string {
    val := reflect.ValueOf(s)
    typ := reflect.TypeOf(s)
    
    var errors []string
    
    for i := 0; i < val.NumField(); i++ {
        field := val.Field(i)
        fieldType := typ.Field(i)
        
        fieldName := fieldType.Name
        rules, exists := v.Rules[fieldName]
        if !exists {
            continue
        }
        
        for _, rule := range rules {
            if !v.checkRule(field, rule) {
                errors = append(errors, fmt.Sprintf("%s failed %s", fieldName, rule))
            }
        }
    }
    
    return errors
}

func (v *Validator) checkRule(field reflect.Value, rule string) bool {
    // Implement rule checking logic
    return true  // placeholder
}
A
Iterate struct fields, check validation rules using reflection
B
Use direct validation
C
Use type assertions
D
Cannot implement validation
30

Question 30

When should you avoid using reflection?

A
In performance-critical code, when you know types at compile time, for simple operations
B
Always use reflection
C
Never avoid reflection
D
Only use reflection
31

Question 31

How do you implement method chaining using reflection?

go
type Builder struct {
    value reflect.Value
}

func NewBuilder(x interface{}) *Builder {
    return &Builder{value: reflect.ValueOf(&x).Elem()}
}

func (b *Builder) Set(field string, value interface{}) *Builder {
    f := b.value.FieldByName(field)
    if f.IsValid() && f.CanSet() {
        f.Set(reflect.ValueOf(value))
    }
    return b
}

func (b *Builder) Get() interface{} {
    return b.value.Interface()
}

func main() {
    type Config struct {
        Host string
        Port int
    }
    
    c := Config{}
    result := NewBuilder(&c).
        Set("Host", "localhost").
        Set("Port", 8080).
        Get()
    
    fmt.Printf("%+v\n", result)
}
A
Use reflection to set fields dynamically and return self for chaining
B
Use direct field access
C
Use maps
D
Cannot implement method chaining
32

Question 32

How do you handle embedded structs with reflection?

go
type Base struct {
    ID int
}

type Derived struct {
    Base
    Name string
}

func main() {
    d := Derived{Base: Base{ID: 1}, Name: "test"}
    v := reflect.ValueOf(d)
    t := reflect.TypeOf(d)
    
    // Iterate all fields including embedded
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        value := v.Field(i)
        
        fmt.Printf("Field: %s, Value: %v, Anonymous: %t\n",
            field.Name, value.Interface(), field.Anonymous)
    }
    
    // Access embedded field directly
    baseField := v.FieldByName("Base")
    idField := baseField.FieldByName("ID")
    fmt.Println("ID:", idField.Interface())
}
A
Embedded fields are treated as regular fields, use field.Anonymous to detect them
B
Use special embedded access
C
Cannot handle embedded structs
D
Use v.Embedded()
33

Question 33

How do you implement a deep copy using reflection?

go
func deepCopy(src interface{}) interface{} {
    srcVal := reflect.ValueOf(src)
    srcType := reflect.TypeOf(src)
    
    dstVal := reflect.New(srcType).Elem()
    copyValue(dstVal, srcVal)
    
    return dstVal.Interface()
}

func copyValue(dst, src reflect.Value) {
    switch src.Kind() {
    case reflect.Ptr:
        if !src.IsNil() {
            dst.Set(reflect.New(src.Type().Elem()))
            copyValue(dst.Elem(), src.Elem())
        }
    case reflect.Struct:
        for i := 0; i < src.NumField(); i++ {
            copyValue(dst.Field(i), src.Field(i))
        }
    case reflect.Slice:
        if !src.IsNil() {
            dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap()))
            for i := 0; i < src.Len(); i++ {
                copyValue(dst.Index(i), src.Index(i))
            }
        }
    default:
        dst.Set(src)
    }
}
A
Recursively copy values based on their Kind
B
Use copy() function
C
Use assignment
D
Cannot implement deep copy
34

Question 34

How do you implement a plugin system using reflection?

go
type Plugin interface {
    Name() string
    Execute(data interface{}) interface{}
}

func loadPlugin(pluginPath string) (Plugin, error) {
    // Load .so file (simplified)
    // p, err := plugin.Open(pluginPath)
    // sym, err := p.Lookup("Plugin")
    // return sym.(Plugin), err
    
    return nil, nil  // placeholder
}

func executePlugin(p Plugin, data interface{}) interface{} {
    // Use reflection to call methods
    v := reflect.ValueOf(p)
    method := v.MethodByName("Execute")
    
    args := []reflect.Value{reflect.ValueOf(data)}
    result := method.Call(args)
    
    return result[0].Interface()
}
A
Load plugins dynamically and use reflection to call methods
B
Use direct function calls
C
Use interfaces directly
D
Cannot implement plugin system
35

Question 35

What is the most important principle for using reflection effectively?

A
Use reflection only when necessary, prefer compile-time solutions, understand performance costs, test thoroughly
B
Always use reflection
C
Never use reflection
D
Use reflection for everything

QUIZZES IN Golang