CodeBlanks Logo Icon CodeBlanks

Summary - Reflection

Combine reflect.Type and Value to write a struct printer.

Reflection summary

In this group you read the type and kind with TypeOf and the contents with ValueOf; changed values through a pointer and Elem; walked struct fields with NumField; and called methods with MethodByName.

t := reflect.TypeOf(v)   // what is it?
val := reflect.ValueOf(v) // what does it hold?

Rule: consider interfaces and generics first; keep reflect for generic tools.

Reading fields by tag

A real example: a tiny encoder that prints struct fields by their tags.

for i := 0; i < t.NumField(); i++ {
    f := t.Field(i)
    fmt.Printf("%s=%v\n", f.Tag.Get("ad"), v.Field(i))
}

JSON, YAML and database libraries essentially use this loop.

Practice Print with tags

Define type Ayar struct { Port int `ad:"port"`; Mod string `ad:"mod"` }. For Ayar{8080, "test"}, print each field as tag=value on its own line (use Tag.Get("ad")).

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

type Ayar struct {
    Port int    `ad:"port"`
    Mod  string `ad:"mod"`
}

func main() {
    a := Ayar{8080, "test"}
    t, v := reflect.TypeOf(a), reflect.ValueOf(a)
    for i := 0; i < t.NumField(); i++ {
        fmt.Printf("%s=%v\n", t.Field(i).Tag.Get("ad"), v.Field(i))
    }
}

Expected output

port=8080
mod=test

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is needed to change a variable with reflect?

  • Passing the variable's pointer and using Elem() Correct answer
  • Passing the variable directly to ValueOf
  • Getting its type with TypeOf
  • Calling NumField

Explanation: ValueOf(x) takes a copy and is not settable; ValueOf(&x).Elem() reaches the real variable.

2 Read the tag

Question
f := t.Field(0)
fmt.Println(f.Tag.____("json"))
Answer
f := t.Field(0)
fmt.Println(f.Tag.Get("json"))

Explanation: Tag.Get returns the tag value for the given key.

3 Group summary

Term Meaning
TypeOf Type and kind
ValueOf Contents
Elem + SetInt Changing the value
MethodByName + Call Dynamic call

All lessons in Advanced