CodeBlanks Logo Icon CodeBlanks

Reflecting struct fields

Learn to access struct fields with reflect.

Iterating struct fields

NumField() gives the number of fields in a struct type; you reach each one with Field(i). The type gives the field name, the value gives its contents.

k := Kitap{Ad: "Dune", Sayfa: 412}
t, v := reflect.TypeOf(k), reflect.ValueOf(k)
for i := 0; i < t.NumField(); i++ {
    fmt.Println(t.Field(i).Name, v.Field(i))
}

Output: Ad Dune and Sayfa 412.

Struct tags and exporting

t.Field(i).Tag.Get("json") reads a field's tag; the JSON package finds field names this way. Unexported fields (lower-case names) can be read but not taken out with Interface() or changed.

type K struct {
    Ad string `json:"ad"`
}
f, _ := reflect.TypeOf(K{}).FieldByName("Ad")
fmt.Println(f.Tag.Get("json"))  // ad

Practice List the fields

Define type Student struct { Ad string; Not int }. For Student{"Ece", 90}, loop over all fields with NumField and print each field name and value on its own line.

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Ad  string
    Not int
}

func main() {
    o := Student{"Ece", 90}
    t, v := reflect.TypeOf(o), reflect.ValueOf(o)
    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Field(i).Name, v.Field(i))
    }
}

Expected output

Ad Ece
Not 90

Questions and answers

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

1 Where do you read a field's <strong>name</strong> from?

  • From the result of NumField()
  • With fmt.Sprint
  • Field(i).Name on the reflect.Type Correct answer
  • Field(i).Int() on the reflect.Value

Explanation: Field name, tag and type belong to the type (StructField); the value side only carries the contents.

2 Field count

Question
for i := 0; i < t.____(); i++ {
Answer
for i := 0; i < t.NumField(); i++ {

Explanation: NumField() returns the number of fields in a struct type.

3 Struct reflect parts

Term Meaning
NumField() Number of fields
Field(i).Name Field name
Tag.Get("json") Tag value
FieldByName Finds a field by name

All lessons in Advanced